使用static embedded
没问题,但在我的情况下,最好定义我自己的"user-type"
并将其添加到 GORM 映射中。
我的班级中只有一个String
带有随机生成的业务密钥的字段,所以我想将此值作为 varchar 存储在 db 中。解决方案是:
在Config.groovy
定义中:
grails.gorm.default.mapping={
"user-type" (type: my.package.persistence.PersistentBookKey, class: BookKey)
}
创建PersistentBookKey
实现UserType
接口的类并覆盖一些方法:
final class PersistentBookKey implements UserType
{
@Override
protected BookKey createKeyFromString(String key) {
BookKey.from(key)
}
@Override
Class returnedClass() {
BookKey
}
private static int [] SQL_TYPES=[Types.VARCHAR] as int[]
@Override
int[] sqlTypes() {
return SQL_TYPES
}
@Override
boolean equals(Object x, Object y) throws HibernateException {
return x.equals(y);
}
@Override
int hashCode(Object x) throws HibernateException {
return x.hashCode()
}
@Override
Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
def key=rs.getString(names[0])
return this.createKeyFromString(key);
}
@Override
void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
BookKey persistent=value as BookKey
st.setString(index,persistent?.getKey())
}
@Override
Object deepCopy(Object value) throws HibernateException {
return value
}
@Override
boolean isMutable() {
return false //To change body of implemented methods use File | Settings | File Templates.
}
@Override
Serializable disassemble(Object value) throws HibernateException {
return value as Serializable
}
@Override
Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached
}
@Override
Object replace(Object original, Object target, Object owner) throws HibernateException {
return original
}
}
现在 BookKey 对象作为 Varchar 存储在数据库中,但是当我得到它们时,它们被转换回 BookKey 对象。
有关更多信息,您可以在这里查看:
http://grails.org/doc/2.0.x/ref/Database%20Mapping/Usage.html
http://grails.1312388.n4.nabble.com/Working-example-of-user-type-td1377468.html