我有一个GORM类,它正在使用嵌入式实例。嵌入式实例是一个不可变类。当我尝试启动应用程序时,它会抛出setter属性未找到异常。
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property amount in class com.xxx.Money.
这是我的GORM课程:
class Billing {
static embedded = ['amount']
Money amount
}
Money定义为不可变:
final class Money {
final Currency currency
final BigDecimal value
Money(Currency currency, BigDecimal value) {
this.currency = currency
this.value = value
}
}
无论如何要解决这个问题而不让Money变得可变?
谢谢!
答案 0 :(得分:1)
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
}