如果您有兴趣,请参考以下代码片段,以获取适当的Hibernate自定义用户类型。首先要扩展PostgreSQL方言以告知它有关json类型的信息,这要归功于Craig Ringer的JAVA_OBJECT指针:
import org.hibernate.dialect.PostgreSQL9Dialect;
import java.sql.Types;
public class JsonPostgreSQLDialect extends PostgreSQL9Dialect {
public JsonPostgreSQLDialect() {
super();
this.registerColumnType(Types.JAVA_OBJECT, "json");
}
}
接下来实现org.hibernate.usertype.UserType。下面的实现将String值映射到json数据库类型,反之亦然。请记住,字符串在Java中是不可变的。也可以使用更复杂的实现将自定义Java Bean映射到数据库中存储的JSON。
package foo;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class StringJsonUserType implements UserType {
@Override
public int[] sqlTypes() {
return new int[] { Types.JAVA_OBJECT};
}
@Override
public Class returnedClass() {
return String.class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if( x== null){
return y== null;
}
return x.equals( y);
}
@Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
if(rs.getString(names[0]) == null){
return null;
}
return rs.getString(names[0]);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.OTHER);
return;
}
st.setObject(index, value, Types.OTHER);
}
@Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
@Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (String)this.deepCopy( value);
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return this.deepCopy( cached);
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}
现在剩下的就是注释实体了。在实体的类声明中添加以下内容:
@TypeDefs( {@TypeDef( name= "StringJsonObject", typeClass = StringJsonUserType.class)})
然后注释属性:
@Type(type = "StringJsonObject")
public String getBar() {
return bar;
}
Hibernate将为您创建带有json类型的列,并来回处理映射。向用户类型实现中注入其他库,以实现更高级的映射。
如果有人想尝试一下,这是一个快速的示例GitHub项目:
https://github.com/timfulmer/hibernate-postgres-jsontype