【问题标题】:grails: counting string size using execute querygrails:使用执行查询计算字符串大小
【发布时间】:2014-02-22 23:05:28
【问题描述】:

我只是想知道是否可以在 Grails 中的单个执行查询中转换这行代码。

String answer = StudentAnswerData.findWhere(student: studentObject, exam: examObject)?.answer

answer.replaceAll('0','')?.size()

代码查询特定的StudentAnswerData,然后计算其答案中非的字符,其中answer是一个由数字组成的字符串字符(例如 2435000025442032030000)。

提前致谢。

【问题讨论】:

  • 除了执行一些特定于数据库的 SQL 之外,Grails 或 GORM 中没有任何东西可以完成此操作。
  • answer.replaceAll('','0') 将在每个字符之前、之后和之间添加一个“0”!是错字吗?
  • 根据问题,看起来 OP 打算写 answer.replaceAll('0','')
  • 您也许可以在域类中添加一个计算计数的方法,然后调用该方法?
  • 对不起,这是一个错字@nickdos。是的,我可以为此创建一个方法,但我只是想知道我是否也可以在 HQL 中使用 StudentAnswerData.executeQuery

标签: grails groovy hql executequery


【解决方案1】:

您可以使用派生属性来做到这一点

http://grails.org/doc/2.3.x/guide/GORM.html#derivedProperties

class StudentAnswerData {
    Integer answerLength
    String answer

    static mapping = {
        answerLength formula: "length(replace(answer, '0', ''))"  //oracle specific syntax
    }
}

然后你可以使用 answerLength 作为常规属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2013-11-16
    • 2022-11-12
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多