一尘不染

是否可以将Hibernate与PostgreSql的JSONB数据类型一起使用?

hibernate

jsonb默认情况下,Hibernate 5不支持PostgreSQL 数据类型。

有什么方法可以实现jsonb对Hibernate + Spring JPA的支持?

如果有办法,jsonb与Hibernate一起使用的利弊是什么?


阅读 474

收藏
2020-06-20

共1个答案

一尘不染

感谢Vlad Mihalcea我们有这样的机会!)

他创建了hibernate类型的 lib:

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

这为Hibernate添加了对’json’,’jsonb’和其他类型的支持:

@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;
}

更多信息:12

2020-06-20