【问题标题】:Grails GORM using immutable embedded objectGrails GORM 使用不可变的嵌入对象
【发布时间】:2014-01-15 08:44:52
【问题描述】:

我有一个使用嵌入式实例的 GORM 类。嵌入的实例是一个不可变的类。当我尝试启动应用程序时,它会抛出 setter property is not found 异常。

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 可变的情况下解决这个问题?

谢谢!

【问题讨论】:

    标签: hibernate grails groovy grails-orm grails-2.0


    【解决方案1】:

    Grails 和 hibernate 通常需要完整的域类是可变的,以支持 hibernate 提供的所有功能。

    您可以使用多列休眠用户类型来存储 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
    }
    

    【讨论】:

    • 我发现的 MoneyUserType 的所有示例看起来都一样,它们都实现了相同的 4 种方法,而仅使用 ... 省略了其余需要的方法。您会通过提供允许可变值的 MoneyUserType 的完整示例来改进您的答案吗?
    猜你喜欢
    • 2015-02-18
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多