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 @   Lafite-1820  阅读(1071)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示