淘先锋技术网

首页 1 2 3 4 5 6 7

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.