将PostgreSQL JSON列映射到Hibernate值类型

Ümi*_*mit 72 java postgresql json hibernate jpa

我的PostgreSQL DB(9.2)中有一个带有JSON类型列的表.我很难将此列映射到JPA2实体字段类型.

我试图使用String,但是当我保存实体时,我得到一个异常,它无法将字符转换为JSON.

处理JSON列时使用的正确值类型是什么?

@Entity
public class MyEntity {

    private String jsonPayload; // this maps to a json column

    public MyEntity() {
    }
}
Run Code Online (Sandbox Code Playgroud)

一个简单的解决方法是定义文本列.

Tim*_*mer 74

如果您有兴趣,可以使用以下几个代码片段来获取Hibernate自定义用户类型.首先扩展PostgreSQL方言以告诉它关于json类型,感谢Craig Ringer的JAVA_OBJECT指针:

import org.hibernate.dialect.PostgreSQL9Dialect;

import java.sql.Types;

/**
 * Wrap default PostgreSQL9Dialect with 'json' type.
 *
 * @author timfulmer
 */
public class JsonPostgreSQLDialect extends PostgreSQL9Dialect {

    public JsonPostgreSQLDialect() {

        super();

        this.registerColumnType(Types.JAVA_OBJECT, "json");
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来实现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;

/**
 * @author timfulmer
 */
public class StringJsonUserType implements UserType {

    /**
     * Return the SQL type codes for the columns mapped by this type. The
     * codes are defined on <tt>java.sql.Types</tt>.
     *
     * @return int[] the typecodes
     * @see java.sql.Types
     */
    @Override
    public int[] sqlTypes() {
        return new int[] { Types.JAVA_OBJECT};
    }

    /**
     * The class returned by <tt>nullSafeGet()</tt>.
     *
     * @return Class
     */
    @Override
    public Class returnedClass() {
        return String.class;
    }

    /**
     * Compare two instances of the class mapped by this type for persistence "equality".
     * Equality of the persistent state.
     *
     * @param x
     * @param y
     * @return boolean
     */
    @Override
    public boolean equals(Object x, Object y) throws HibernateException {

        if( x== null){

            return y== null;
        }

        return x.equals( y);
    }

    /**
     * Get a hashcode for the instance, consistent with persistence "equality"
     */
    @Override
    public int hashCode(Object x) throws HibernateException {

        return x.hashCode();
    }

    /**
     * Retrieve an instance of the mapped class from a JDBC resultset. Implementors
     * should handle possibility of null values.
     *
     * @param rs      a JDBC result set
     * @param names   the column names
     * @param session
     * @param owner   the containing entity  @return Object
     * @throws org.hibernate.HibernateException
     *
     * @throws java.sql.SQLException
     */
    @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]);
    }

    /**
     * Write an instance of the mapped class to a prepared statement. Implementors
     * should handle possibility of null values. A multi-column type should be written
     * to parameters starting from <tt>index</tt>.
     *
     * @param st      a JDBC prepared statement
     * @param value   the object to write
     * @param index   statement parameter index
     * @param session
     * @throws org.hibernate.HibernateException
     *
     * @throws java.sql.SQLException
     */
    @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);
    }

    /**
     * Return a deep copy of the persistent state, stopping at entities and at
     * collections. It is not necessary to copy immutable objects, or null
     * values, in which case it is safe to simply return the argument.
     *
     * @param value the object to be cloned, which may be null
     * @return Object a copy
     */
    @Override
    public Object deepCopy(Object value) throws HibernateException {

        return value;
    }

    /**
     * Are objects of this type mutable?
     *
     * @return boolean
     */
    @Override
    public boolean isMutable() {
        return true;
    }

    /**
     * Transform the object into its cacheable representation. At the very least this
     * method should perform a deep copy if the type is mutable. That may not be enough
     * for some implementations, however; for example, associations must be cached as
     * identifier values. (optional operation)
     *
     * @param value the object to be cached
     * @return a cachable representation of the object
     * @throws org.hibernate.HibernateException
     *
     */
    @Override
    public Serializable disassemble(Object value) throws HibernateException {
        return (String)this.deepCopy( value);
    }

    /**
     * Reconstruct an object from the cacheable representation. At the very least this
     * method should perform a deep copy if the type is mutable. (optional operation)
     *
     * @param cached the object to be cached
     * @param owner  the owner of the cached object
     * @return a reconstructed object from the cachable representation
     * @throws org.hibernate.HibernateException
     *
     */
    @Override
    public Object assemble(Serializable cached, Object owner) throws HibernateException {
        return this.deepCopy( cached);
    }

    /**
     * During merge, replace the existing (target) value in the entity we are merging to
     * with a new (original) value from the detached entity we are merging. For immutable
     * objects, or null values, it is safe to simply return the first parameter. For
     * mutable objects, it is safe to return a copy of the first parameter. For objects
     * with component values, it might make sense to recursively replace component values.
     *
     * @param original the value from the detached entity being merged
     * @param target   the value in the managed entity
     * @return the value to be merged
     */
    @Override
    public Object replace(Object original, Object target, Object owner) throws HibernateException {
        return original;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在剩下的就是注释实体.把这样的东西放在实体的类声明中:

@TypeDefs( {@TypeDef( name= "StringJsonObject", typeClass = StringJsonUserType.class)})
Run Code Online (Sandbox Code Playgroud)

然后注释属性:

@Type(type = "StringJsonObject")
public String getBar() {
    return bar;
}
Run Code Online (Sandbox Code Playgroud)

Hibernate将负责为您创建具有json类型的列,并来回处理映射.将其他库注入用户类型实现以获得更高级的映射.

这是一个快速示例GitHub项目,如果有人想玩它:

https://github.com/timfulmer/hibernate-postgres-jsontype

  • 我没有看到链接[github-project]上的任何代码(https://github.com/timfulmer/hibernate-postgres-jsontype);-)顺便说一句:将此代码作为库是否有用重用? (7认同)
  • 你的nullSafeGet实现代码有问题.而不是if(rs.wasNull())你应该做if(rs.getString(names [0])== null).我不确定rs.wasNull()是做什么的,但在我的情况下,它通过返回true来烧毁我,当我寻找的值实际上不是null时. (3认同)
  • 这个解决方案与Hibernate 4.2.7很好地兼容,除非从json列检索null时出现错误'JDBC Dialect mapping for JDBC type:1111'.但是,在dialect类中添加以下行来修复它:this.registerHibernateType(Types.OTHER,"StringJsonUserType"); (3认同)
  • 不用担心,我最终得到了代码和这个页面在我面前,并想出为什么不:)这可能是Java过程的缺点.我们通过解决棘手问题的方法得到了很好的考虑,但要进入并为新类型添加类似通用SPI的好主意并不容易.我们留下了任何实施者,在这种情况下,Hibernate,到位. (2认同)

Cra*_*ger 37

见PgJDBC bug#265.

PostgreSQL对数据类型转换过于严格,非常严格.它不会隐式地text转换为类似文本的值,例如xmljson.

解决此问题的严格正确方法是编写使用JDBC setObject方法的自定义Hibernate映射类型.这可能有点麻烦,所以你可能只想通过创建一个较弱的强制转换来使PostgreSQL不那么严格.

正如@markdsievers在评论和此博客文章中所指出的,此答案中的原始解决方案绕过了JSON验证.所以这不是你想要的.写起来更安全:

CREATE OR REPLACE FUNCTION json_intext(text) RETURNS json AS $$
SELECT json_in($1::cstring); 
$$ LANGUAGE SQL IMMUTABLE;

CREATE CAST (text AS json) WITH FUNCTION json_intext(text) AS IMPLICIT;
Run Code Online (Sandbox Code Playgroud)

AS IMPLICIT 告诉PostgreSQL它可以转换而不被明确告知,允许这样的事情工作:

regress=# CREATE TABLE jsontext(x json);
CREATE TABLE
regress=# PREPARE test(text) AS INSERT INTO jsontext(x) VALUES ($1);
PREPARE
regress=# EXECUTE test('{}')
INSERT 0 1
Run Code Online (Sandbox Code Playgroud)

感谢@markdsievers指出了这个问题.

  • 值得一读这个答案的结果[博客文章](http://www.pateldenish.com/2013/05/inserting-json-data-into-postgres-using-jdbc-driver.html).特别是评论部分突出了这个的危险(允许无效的json)和替代/优越的解决方案. (2认同)

Vla*_*cea 14

正如我在本文中解释的那样,使用Hibernate持久化JSON对象非常容易.

您不必手动创建所有这些类型,只需使用以下依赖项通过Maven Central获取它们:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version> 
</dependency> 
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看hibernate类型的开源项目.

现在,解释它是如何工作的.

我写了一篇关于如何在PostgreSQL和MySQL上映射JSON对象的文章.

对于PostgreSQL,您需要以二进制形式发送JSON对象:

public class JsonBinaryType
    extends AbstractSingleColumnStandardBasicType<Object> 
    implements DynamicParameterizedType {

    public JsonBinaryType() {
        super( 
            JsonBinarySqlTypeDescriptor.INSTANCE, 
            new JsonTypeDescriptor()
        );
    }

    public String getName() {
        return "jsonb";
    }

    @Override
    public void setParameterValues(Properties parameters) {
        ((JsonTypeDescriptor) getJavaTypeDescriptor())
            .setParameterValues(parameters);
    }

}
Run Code Online (Sandbox Code Playgroud)

JsonBinarySqlTypeDescriptor如下所示:

public class JsonBinarySqlTypeDescriptor
    extends AbstractJsonSqlTypeDescriptor {

    public static final JsonBinarySqlTypeDescriptor INSTANCE = 
        new JsonBinarySqlTypeDescriptor();

    @Override
    public <X> ValueBinder<X> getBinder(
        final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicBinder<X>(javaTypeDescriptor, this) {
            @Override
            protected void doBind(
                PreparedStatement st, 
                X value, 
                int index, 
                WrapperOptions options) throws SQLException {
                st.setObject(index, 
                    javaTypeDescriptor.unwrap(
                        value, JsonNode.class, options), getSqlType()
                );
            }

            @Override
            protected void doBind(
                CallableStatement st, 
                X value, 
                String name, 
                WrapperOptions options)
                    throws SQLException {
                st.setObject(name, 
                    javaTypeDescriptor.unwrap(
                        value, JsonNode.class, options), getSqlType()
                );
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

JsonTypeDescriptor类的:

public class JsonTypeDescriptor
        extends AbstractTypeDescriptor<Object> 
        implements DynamicParameterizedType {

    private Class<?> jsonObjectClass;

    @Override
    public void setParameterValues(Properties parameters) {
        jsonObjectClass = ( (ParameterType) parameters.get( PARAMETER_TYPE ) )
            .getReturnedClass();

    }

    public JsonTypeDescriptor() {
        super( Object.class, new MutableMutabilityPlan<Object>() {
            @Override
            protected Object deepCopyNotNull(Object value) {
                return JacksonUtil.clone(value);
            }
        });
    }

    @Override
    public boolean areEqual(Object one, Object another) {
        if ( one == another ) {
            return true;
        }
        if ( one == null || another == null ) {
            return false;
        }
        return JacksonUtil.toJsonNode(JacksonUtil.toString(one)).equals(
                JacksonUtil.toJsonNode(JacksonUtil.toString(another)));
    }

    @Override
    public String toString(Object value) {
        return JacksonUtil.toString(value);
    }

    @Override
    public Object fromString(String string) {
        return JacksonUtil.fromString(string, jsonObjectClass);
    }

    @SuppressWarnings({ "unchecked" })
    @Override
    public <X> X unwrap(Object value, Class<X> type, WrapperOptions options) {
        if ( value == null ) {
            return null;
        }
        if ( String.class.isAssignableFrom( type ) ) {
            return (X) toString(value);
        }
        if ( Object.class.isAssignableFrom( type ) ) {
            return (X) JacksonUtil.toJsonNode(toString(value));
        }
        throw unknownUnwrap( type );
    }

    @Override
    public <X> Object wrap(X value, WrapperOptions options) {
        if ( value == null ) {
            return null;
        }
        return fromString(value.toString());
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,您需要在类级别或package-info.java包级别描述符中声明新类型:

@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
Run Code Online (Sandbox Code Playgroud)

实体映射将如下所示:

@Type(type = "jsonb")
@Column(columnDefinition = "json")
private Location location;
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Hibernate 5或更高版本,则Postgre92Dialect会自动注册JSON类型.

否则,您需要自己注册:

public class PostgreSQLDialect extends PostgreSQL91Dialect {

    public PostgreSQL92Dialect() {
        super();
        this.registerColumnType( Types.JAVA_OBJECT, "json" );
    }
}
Run Code Online (Sandbox Code Playgroud)


vas*_*ily 11

如果有人感兴趣,您可以在Hibernate中使用JPA 2.1 @Convert/ @Converter功能.您必须使用pgjdbc-ng JDBC驱动程序.这样您就不必每个字段使用任何专有扩展,方言和自定义类型.

@javax.persistence.Converter
public static class MyCustomConverter implements AttributeConverter<MuCustomClass, String> {

    @Override
    @NotNull
    public String convertToDatabaseColumn(@NotNull MuCustomClass myCustomObject) {
        ...
    }

    @Override
    @NotNull
    public MuCustomClass convertToEntityAttribute(@NotNull String databaseDataAsJSONString) {
        ...
    }
}

...

@Convert(converter = MyCustomConverter.class)
private MyCustomClass attribute;
Run Code Online (Sandbox Code Playgroud)


Tom*_*yQu 5

我尝试了网上找到的很多方法,大部分都行不通,有的太复杂了。下面的一个对我有用,如果你对 PostgreSQL 类型验证没有那么严格的要求,它会简单得多。

将 PostgreSQL jdbc 字符串类型设为未指定,例如 <connection-url> jdbc:postgresql://localhost:test?stringtype=??unspecified </connect??ion-url>