当我创建一个通用类将其嵌入到其他类时,我想添加一个由公式定义的瞬态属性,但我不知道如何实现它。这是我的源代码:
//Embedded
class LocationInfo {
Long country, state, city
String address, fullAddress
static constraints = {
country nullable: true
state nullable: true
city nullable: true
address nullable: true
}
static mapping = {
country column: 'l_country'
state column: 'l_state'
city column: 'l_city'
address column: 'l_address'
fullAddress formula: "SELECT (l_address || ', ' || city.name) FROM system_location city WHERE city.id = l_city"
}
static transients = ['fullAddress']
}
class SystemLocation {
String name
Long parentLocationId
String level
static constraints = {
name blank: false, maxSize: 100
parentLocationId nullable: true
level inList: ['country', 'state', 'city']
}
static mapping = { version false }
}
//Host
class User {
String email
String password
String firstName
String lastName
Team team
UserLevel userLevel
boolean enabled = true
boolean accountExpired = false
boolean accountLocked = false
boolean passwordExpired = false
boolean teamLeader = false
LocationInfo locationInfo
AuditingInfo auditingInfo
static embedded = ['locationInfo', 'auditingInfo']
transient springSecurityService
static constraints = {
email blank: false, unique: true, maxSize: 200
password blank: false, maxSize: 200
firstName blank: false
lastName blank: false
team nullable: true
teamLeader nullable: true
locationInfo nullable: true
auditingInfo nullable: true
}
static mapping = {
team column: "team_id"
userLevel column: "user_level_id"
}
}
LocationInfo
嵌入到User
类,nhưng当我按ID获取特定用户并检查user.locationInfo.fullAddress
中的值时,它始终为NULL;并且生成的SQL不包含“SELECT(l_address ||','|| city.name)...”语句。
我不知道如何在嵌入式类中使用公式。
你能帮我解决一下吗?
答案 0 :(得分:0)
根据Grails手册,地图设置中没有formula
这样的内容。
我只需在你的域类中声明一个getter方法来解决这个问题:
class LocationInfo {
Long country, state,
SystemLocation city
String address // n.b. no longAddress here
static constraints = {
country nullable: true
state nullable: true
city nullable: true
address nullable: true
}
static mapping = {
country column: 'l_country'
state column: 'l_state'
address column: 'l_address'
}
static transients = ['fullAddress']
String getFullAddress() {
"$address $city.name"
}
}
N.B。该城市现在是对另一个域类的引用。在您的草稿中,这只是一个使您的域模型难以导航的ID。
答案 1 :(得分:0)
我也有这个问题,我认为你不能这样做。
为某些派生属性定义公式时,必须将SQL与您知道的列名称放在一起。但是当嵌入属性中使用此类时,该嵌入对象的列名称将被更改。
在您的案例表中,用户具有列location_info_l_city,location_info_l_address。但是在公式中你使用了像l_city,l_address这样的名字......表User中没有这样的列。
我通过为嵌入对象的所有者添加派生属性来解决问题。 在您的情况下,我将添加到类用户映射:
class User {
//...
String fullAddress
//...
static mapping = {
//...
fullAddress formula: "SELECT (location_info_l_address || ', ' || city.name) FROM system_location city WHERE city.id = location_info_l_city"
}
}
现在,您也可以在HQL查询中使用列User.fullAddress。