使用视图或将它们保存在数据库中的计算字段
Calculated fields using views or persisting them in the database
我想知道哪个更好用,数据库视图还是简单地在数据库中保留字段。
例如,我在以下视图 vw_stats
:
中初始化 win_count
...
CASE
WHEN game.in_decision = true AND game.user_score > game.opponent_score THEN 1
ELSE 0
END AS win_count,
...
然后映射到域 class:
package com.x
class Stat {
//fields here...
static mapping = {
table 'vw_stats'
version false
}
}
或者,我是否应该使用此域 class 将字段 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
}
}
我发现的视图问题是,当 运行 应用程序时它会生成 table,然后我必须手动删除 table 和 运行 生成视图的代码。
更新 #1
将它们保存在数据库而不是视图中可能会节省 IO 成本?
更新 #2
忘了说了,我应该可以在服务的结果字段上应用聚合函数。
第三种方法是使用 derived 属性。与视图一样,该值是即时计算的。
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'
}
}
不完全了解您要实现的确切应用,您是否考虑过使用 transients 并让领域实例在实际需要时计算它?这将避免预先计算甚至可能不会使用的数据。
我想知道哪个更好用,数据库视图还是简单地在数据库中保留字段。
例如,我在以下视图 vw_stats
:
win_count
...
CASE
WHEN game.in_decision = true AND game.user_score > game.opponent_score THEN 1
ELSE 0
END AS win_count,
...
然后映射到域 class:
package com.x
class Stat {
//fields here...
static mapping = {
table 'vw_stats'
version false
}
}
或者,我是否应该使用此域 class 将字段 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
}
}
我发现的视图问题是,当 运行 应用程序时它会生成 table,然后我必须手动删除 table 和 运行 生成视图的代码。
更新 #1 将它们保存在数据库而不是视图中可能会节省 IO 成本?
更新 #2 忘了说了,我应该可以在服务的结果字段上应用聚合函数。
第三种方法是使用 derived 属性。与视图一样,该值是即时计算的。
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'
}
}
不完全了解您要实现的确切应用,您是否考虑过使用 transients 并让领域实例在实际需要时计算它?这将避免预先计算甚至可能不会使用的数据。