单体映射为Map,数组映射为List

1.Map的映射

1.使用Map数据类型

  1. private Map<String, Object> specs;

2.编写一个MapAndJson类进行转换

该类实现了AttributeConverter<>接口

  1. public class MapAndJson implements AttributeConverter<Map<String,Object>,String> {
  2. }

3.在类中调用ObjectMapper的方法完成格式之间的相互转换

  1. public class MapAndJson implements AttributeConverter<Map<String,Object>,String> {
  2. @Autowired
  3. private ObjectMapper mapper;
  4. @Override
  5. public String convertToDatabaseColumn(Map<String, Object> stringObjectMap) {
  6. try {
  7. return mapper.writeValueAsString(stringObjectMap);
  8. } catch (JsonProcessingException e) {
  9. e.printStackTrace();
  10. throw new ServerErrorException(9999);
  11. }
  12. }
  13. @Override
  14. public Map<String, Object> convertToEntityAttribute(String s) {
  15. try {
  16. return mapper.readValue(s, HashMap.class);
  17. } catch (JsonProcessingException e) {
  18. throw new ServerErrorException(9999);
  19. }
  20. }
  21. }

4.使用@Convert注解注入

  1. @Convert(converter = MapAndJson.class)
  2. private Map<String, Object> specs;

2.List的映射:

大体与Map相同,但在映射类中代码需要更改

  1. @Converter
  2. public class ListAndJson implements AttributeConverter<List<Object>,String> {
  3. @Autowired
  4. private ObjectMapper mapper;
  5. @Override
  6. public String convertToDatabaseColumn(List<Object> objects) {
  7. try {
  8. return mapper.writeValueAsString(objects);
  9. } catch (JsonProcessingException e) {
  10. e.printStackTrace();
  11. throw new ServerErrorException(9999);
  12. }
  13. }
  14. @Override
  15. public List<Object> convertToEntityAttribute(String s) {
  16. try {
  17. if (s == null){
  18. return null;
  19. }
  20. List<Object> t = mapper.readValue(s,List.class);
  21. return t;
  22. } catch (JsonProcessingException e) {
  23. e.printStackTrace();
  24. throw new ServerErrorException(9999);
  25. }
  26. }
  27. }