我有一个 GORM 类,它在其中使用嵌入实例。并且嵌入的实例是一个不可变的类。当我尝试启动应用程序时,它抛出 setter 属性未找到异常。
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property amount in class com.xxx.Money.
这是我的 GORM 类(class):
class Billing {
static embedded = ['amount']
Money amount
}
金钱被定义为不可变的:
final class Money {
final Currency currency
final BigDecimal value
Money(Currency currency, BigDecimal value) {
this.currency = currency
this.value = value
}
}
有办法在不使 Money 可变的情况下解决这个问题吗?
谢谢!
最佳答案
Grails 和 hibernate 通常需要完整的域类是可变的,以支持 hibernate 提供的所有功能。
您可以使用多列 hibernate UserType 来存储 Money 金额,而不是嵌入 Money 域类。以下是如何编写 UserType 的示例:
import java.sql.*
import org.hibernate.usertype.UserType
class MoneyUserType implements UserType {
int[] sqlTypes() {
[Types.VARCHAR, Types.DECIMAL] as int[]
}
Class returnedClass() {
Money
}
def nullSafeGet(ResultSet resultSet, String[] names, Object owner) HibernateException, SQLException {
String currency = resultSet.getString(names[0])
BigDecimal value = resultSet.getBigDecimal(names[1])
if (currency != null && value != null) {
new Money(currency, value)
} else {
new Money("", 0.0)
}
}
void nullSafeSet(PreparedStatement statement, Object money, int index) {
statement.setString(index, money?.currency ?: "")
statement.setBigDecimal(index+1, money?.value ?: 0.0)
}
...
}
要在域类中使用它,请将字段映射到 UserType 而不是嵌入它:
class Billing {
static mapping = {
amount type: MoneyUserType
}
Money amount
}
关于hibernate - 使用不可变嵌入对象的 Grails GORM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20806095/