我尝试配置这样的域类:
class Test {
String data
static constraints = {
}
static mapping = {
data type: 'jsonb'
}
}
这会引发异常(最终的原因是Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: jsonb, at table: test, for columns: [org.hibernate.mapping.Column(data)]
).
我也尝试过column: 'data', sqlType: 'jsonb'
,这会创建一个text
列名为data
.
我如何正确告诉 grails 使用jsonb
作为sql列类型?这有可能吗?
(postgresql jdbc 驱动程序在版本 9.4-1200.jdbc4 和 hibernate 4 中使用。)
配置要映射的域jsonb
键入至String
你可以:
-
声明你自己的org.hibernate.usertype.UserType
。添加src/java
:
public class JSONBType implements UserType {
@Override
public int[] sqlTypes() {
return new int[] { Types.OTHER };
}
@SuppressWarnings("rawtypes")
@Override
public Class returnedClass() {
return String.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
return (x != null) && x.equals(y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor sessionImplementor, Object owner)
throws HibernateException, SQLException {
return rs.getString(names[0]);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor sessionImplementor)
throws HibernateException, SQLException {
st.setObject(index, value, (value == null) ? Types.NULL : Types.OTHER);
}
@Override
public Object deepCopy(Object value) throws HibernateException {
if (value == null) return null;
return new String((String)value);
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable)value;
}
@Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return deepCopy(original);
}
}
-
之后,您可以简单地在域中声明映射:
static mapping = {
data type: "your.package.JSONBType", sqlType: "jsonb"
}
还可以映射jsonb
not to String
,但直接到JSONObject
或您现有的类或接口。在这种情况下,GORM 将负责序列化/反序列化 json,并且您不再需要在应用程序中显式执行此操作。这是一个这样的例子UserType执行 https://github.com/pires/hibernate-postgres-jsonb/blob/master/src/main/java/com/github/pires/example/hibernate/user/types/JSONBUserType.java.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)