Search code examples
javamysqljsonhibernatejpa

How to map a MySQL JSON column to a Java entity property using JPA and Hibernate


I have a 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;

Solution

  • 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<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.