jpa和postgres实现保存json格式数据

maven包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
</dependency>
<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>2.3.4</version>
</dependency>

com.vladmihalcea hibernate-types-52 2.3.4
这个包提供了一个JsonBinaryType的hibernate的type实现。免去自己去定义Type。

如何使用

文章类


@Entity
@EntityListeners(AuditingEntityListener.class)
@Data
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class Article {

    @Id
    @GeneratedValue
    private long id;
  
    /**
     * 图片
     */
    @Type(type = "jsonb")
    @Column(columnDefinition = "jsonb")
    private List<DocumentFile> documentFiles = new ArrayList<>();

    @CreatedDate
    private long createdDate;
    @CreatedBy
    private long createdBy;
    @LastModifiedDate
    private long lastModifiedDate;
    @LastModifiedBy
    private long lastModifiedBy;
}

附件类

@Data
public class DocumentFile implements Serializable {
    private static final long serialVersionUID = 2642228880622807382L;
    private String name;
    private String extension;
    private String miniType;
    private String contentType;
    private String fileHash;
    private long fileSize;
    private String location;
    private long locationExpired;
}

json格式类,需要实现序列化。然后在引用的地方要加上如下代码:

@TypeDef(name = “jsonb”, typeClass = JsonBinaryType.class)

加在引用类的类名上。例子中也就是Article类上面

@Type(type = “jsonb”)
@Column(columnDefinition = “jsonb”)

加在引用类的对应属性名上,例子中也就是,documentFiles 上面。

文章来源:https://blog.csdn.net/nickzhang2016/article/details/108054524

posted @ 2022-11-09 11:29  Lafite-1820  阅读(1152)  评论(1)    收藏  举报