如何使用JPA和Hibernate将MySQL JSON列映射到Java实体属性- [英] How to map a MySQL JSON column to a Java entity property using JPA and Hibernate -

查看:881
本文介绍了如何使用JPA和Hibernate将MySQL JSON列映射到Java实体属性-的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将MySQL列声明为类型 JSON ,并且在使用Jpa/Hibernate映射时遇到了问题.我在后端使用Spring Boot.

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.

在mysql表中,该列定义为:

In mysql table the column is defined as:

json_value JSON NOT NULL;

json_value JSON NOT NULL;

推荐答案

我更喜欢这样做:

  • 创建从Map到String的转换器(属性转换器),反之亦然.
  • 使用Map映射域(实体)类中的mysql JSON列类型

代码在下面.

JsonToMapConverted.java

JsonToMapConverted.java

@Converter
public class JsonToMapConverter 
                    implements AttributeConverter<String, Map<String, Object>> 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonToMapConverter.class);

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> 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<String, Object> 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<String, Object> metaData = new HashMap<>();

...

此解决方案非常适合我.

This solution perfectly works for me.

这篇关于如何使用JPA和Hibernate将MySQL JSON列映射到Java实体属性-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆