jpa 映射 mysql json 对象
测试数据:
其中,tagIDList为json类型
[{"tagID": "1", "tagName": "tag1"}, {"tagID": "2", "tagName": "tag2"}]
那我们怎么通过jpa映射呢?
一,添加依赖
<!-- https://mvnrepository.com/artifact/com.vladmihalcea/hibernate-types-52 --> <dependency> <groupId>com.vladmihalcea</groupId> <artifactId>hibernate-types-52</artifactId> <version>2.12.1</version> </dependency>
二,Entity添加注解
1 @TypeDef(name = "json", typeClass = JsonStringType.class)
2 @Type(type = "json")
3 @Column(name="tagIDList",columnDefinition = "json" )
import com.vladmihalcea.hibernate.type.json.JsonStringType; import lombok.Data; import org.hibernate.annotations.*; import javax.persistence.*; import javax.persistence.Entity; import javax.persistence.Table; import java.util.Date; import java.util.List; /** * 广告模型 */ @Data @Entity @Table(name="ad_advertisement",catalog = "ss_business") @TypeDef(name = "json", typeClass = JsonStringType.class) public class AdAdvertisement extends SuperBaseModel { /** * 标签 */ @Type(type = "json") @Column(name="tagIDList",columnDefinition = "json" ) private List<AdTag> tagIDList; }
看一下AdTag
package com.tenyears.webAD.model; import com.tenyears.model.base.SuperBaseModel; import lombok.Data; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; /** * 标签模型 */ @Data @Entity @Table(name="ad_tag",catalog = "ss_business") public class AdTag { /** * 主键 */ @Id private long tagID; /** * 标签名 */ @Column(name="tagName") private String tagName; }
三,请求验证