Is it possible to use Hibernate with PostgreSql's JSONB data type?

妖精的绣舞 提交于 2019-12-04 10:41:51

问题


Hibernate 5 does not support the PostgreSQL jsonb data type by default.

Is there any way to implement jsonb support for Hibernate + Spring JPA?

If there is a way, what are the pros and cons of using jsonb with Hibernate?


回答1:


Thanks Vlad Mihalcea we have such opportunity! )

He created hibernate-types lib:

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>2.1.1</version>
</dependency> 

which adds a support of 'json', 'jsonb' and other types to Hibernate:

@Data
@NoArgsConstructor
@Entity
@Table(name = "parents")
@TypeDefs({
        @TypeDef(name = "string-array", typeClass = StringArrayType.class),
        @TypeDef(name = "int-array", typeClass = IntArrayType.class),
        @TypeDef(name = "json", typeClass = JsonStringType.class),
        @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class Parent implements Serializable {

    @Id
    @GeneratedValue(strategy = SEQUENCE)
    private Integer id;

    @Column(length = 32, nullable = false)
    private String name;

    @Type(type = "jsonb")
    @Column(columnDefinition = "jsonb")
    private List<Child> children;

    @Type(type = "string-array")
    @Column(columnDefinition = "text[]")
    private String[] phones;

    public Parent(String name, List<Child> children, String... phones) {
        this.name = name;
        this.children = children;
        this.phones = phones;
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Child implements Serializable {
    private String name;
}

More info: 1, 2




回答2:


@Cepr0-s answer is correct but although I got some issues with it. I was getting exception when trying to use it with PostgreSQL org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111. Way to solve this, in my case, was adding custom hibernate dialect. This resource might be helpful.

// CustomPostgreSQLDialect.java
public class CustomPostgreSQLDialect extends PostgreSQL10Dialect {

    public CustomPostgreSQLDialect() {
        super();
        registerHibernateType(Types.OTHER, StringArrayType.class.getName());
        registerHibernateType(Types.OTHER, IntArrayType.class.getName());
        registerHibernateType(Types.OTHER, JsonStringType.class.getName());
        registerHibernateType(Types.OTHER, JsonBinaryType.class.getName());
        registerHibernateType(Types.OTHER, JsonNodeBinaryType.class.getName());
        registerHibernateType(Types.OTHER, JsonNodeStringType.class.getName());
    }
}

-

# application.yml
spring:
  jpa:
    properties:
      hibernate:
        dialect: "com.test.CustomPostgreSQLDialect"


来源:https://stackoverflow.com/questions/49325802/is-it-possible-to-use-hibernate-with-postgresqls-jsonb-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!