单体映射为Map,数组映射为List
1.Map的映射
1.使用Map数据类型
private Map<String, Object> specs;
2.编写一个MapAndJson类进行转换
该类实现了AttributeConverter<>接口
public class MapAndJson implements AttributeConverter<Map<String,Object>,String> {
}
3.在类中调用ObjectMapper的方法完成格式之间的相互转换
public class MapAndJson implements AttributeConverter<Map<String,Object>,String> {
@Autowired
private ObjectMapper mapper;
@Override
public String convertToDatabaseColumn(Map<String, Object> stringObjectMap) {
try {
return mapper.writeValueAsString(stringObjectMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new ServerErrorException(9999);
}
}
@Override
public Map<String, Object> convertToEntityAttribute(String s) {
try {
return mapper.readValue(s, HashMap.class);
} catch (JsonProcessingException e) {
throw new ServerErrorException(9999);
}
}
}
4.使用@Convert注解注入
@Convert(converter = MapAndJson.class)
private Map<String, Object> specs;
2.List的映射:
大体与Map相同,但在映射类中代码需要更改
@Converter
public class ListAndJson implements AttributeConverter<List<Object>,String> {
@Autowired
private ObjectMapper mapper;
@Override
public String convertToDatabaseColumn(List<Object> objects) {
try {
return mapper.writeValueAsString(objects);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new ServerErrorException(9999);
}
}
@Override
public List<Object> convertToEntityAttribute(String s) {
try {
if (s == null){
return null;
}
List<Object> t = mapper.readValue(s,List.class);
return t;
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new ServerErrorException(9999);
}
}
}