hibernate mysql 序列化_如何使用JPA和Hibernate将MySQL JSON列映射到Java实体属性

bd96500e110b49cbb3cd949968f18be7.png

I have MySQL column declared as type JSON and I have problems to map it with Jpa/Hibernate. I'm using Spring Boot on back-end.

Here is small part of my code:

@Entity

@Table(name = "some_table_name")

public class MyCustomEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;

@Column(name = "json_value")

private JSONArray jsonValue;

The program returns me an error and tells me that I can't map the column.

In mysql table the column is defined as:

json_value JSON NOT NULL;

解决方案

I prefer to do this way:

Creating converter (attribute converter) from Map to String and vice versa.

Using Map to map mysql JSON column type in domain (entity) class

The code is bellow.

JsonToMapConverted.java

@Converter

public class JsonToMapConverter

implements AttributeConverter>

{

private static final Logger LOGGER = LoggerFactory.getLogger(JsonToMapConverter.class);

@Override

@SuppressWarnings("unchecked")

public Map convertToDatabaseColumn(String attribute)

{

if (attribute == null) {

return new HashMap<>();

}

try

{

ObjectMapper objectMapper = new ObjectMapper();

return objectMapper.readValue(attribute, HashMap.class);

}

catch (IOException e) {

LOGGER.error("Convert error while trying to convert string(JSON) to map data structure.");

}

return new HashMap<>();

}

@Override

public String convertToEntityAttribute(Map dbData)

{

try

{

ObjectMapper objectMapper = new ObjectMapper();

return objectMapper.writeValueAsString(dbData);

}

catch (JsonProcessingException e)

{

LOGGER.error("Could not convert map to json string.");

return null;

}

}

}

Part of domain (entity-mapping) class

...

@Column(name = "meta_data", columnDefinition = "json")

@Convert(attributeName = "data", converter = JsonToMapConverter.class)

private Map metaData = new HashMap<>();

...

This solution perfectly works for me.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值