grails - 使用 View 或将其保留在数据库中的计算字段

标签 grails gorm

我想知道哪种更好用,是数据库 View 还是仅将字段保留在数据库中。

例如,我正在以下 View win_count中初始化vw_stats:

...
CASE
    WHEN game.in_decision = true AND game.user_score > game.opponent_score THEN 1
    ELSE 0
END AS win_count,
...

然后将其映射到域类:
package com.x

class Stat {

    //fields here...

    static mapping = {
        table 'vw_stats'
        version false
    }
}

或者,是否应该使用此域类将字段winCount保留在数据库中并在保存之前对其进行操作?
package com.x

class Game {

    //fields here...
    Short winCount = 0


  static constraints = {
      //constraints here...        
      winCount nullable: false, range: 0..99

  }

  def beforeInsert(){
      this.beforeUpdate()
  }

  def beforeUpdate(){

      //other manipulations here...
      if inDecision and userScore > opponentScore
          winCount = 1
  }

}

我发现的 View 问题是,它将在运行应用程序时生成一个表,然后我必须手动删除该表并运行代码以生成 View 。

更新#1
通过将它们持久保存在数据库而不是 View 中,可能会节省IO成本?

更新#2
忘了提一下,我应该能够在服务的结果字段上应用聚合函数。

最佳答案

第三种方法是使用derived属性。与 View 一样,该值是动态计算的。

package com.x

class Game {

    //fields here...
    Short winCount = 0

  static constraints = {
      //constraints here...        
      winCount nullable: false, range: 0..99

  }

    static mapping = {
        winCount formula: 'CASE WHEN in_decision = true AND user_score > opponent_score THEN 1 ELSE 0 END'
    }

}

关于grails - 使用 View 或将其保留在数据库中的计算字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226795/

相关文章:

grails - DirContextOperations 为空

mongodb - 在Grails 3.1.x和Mongo 5.0.x插件中使用java.util.Set域属性

hibernate - Groovy/Grails:不区分大小写,使用 `findAllBy … InList`进行过滤

grails - 我在grails-app conf文件夹中找不到数据源文件夹

java - 如何在单个集合中获取 grails 域类的所有持久属性及其约束?

grails - Grails 2.5.3无法解析 Controller 上的消息参数

Grails:访问 main.gsp 布局中的模型

grails - 如何在grails中为createCriteria的从和到日期之间写从句?

grails - Grails 2.3.x升级产生重复hasMany关系

hibernate - 在 hibernate 过滤器中运行代码