@Convert属性转换器用于数据库属性类型与java存储的类型做转换,其方便之处在于存储与读取的时候能自动转换,如下业务场景:
业务对象存在一个Map或List属性,存入数据库时需保存为json字符串,返回前端时以对象来返回。
@Convert属性转换器需实现AttributeConverter<X, Y>接口,第一个泛型类型为Entity字段类型,第二个泛型类型为数据库字段类型。
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import javax.persistence.AttributeConverter; import java.util.HashMap; import java.util.Map; /** * @Description Map与JSON映射转换器 * @author coisini * @date Aug 16, 2021 * @Version 1.0 */ public class MapAndJson implements AttributeConverter<Map<String, Object>, String> { @Autowired private ObjectMapper mapper; /** * 转换成数据库字段 * @param stringObjectMap * @return */ @Override public String convertToDatabaseColumn(Map<String, Object> stringObjectMap) { try { return mapper.writeValueAsString(stringObjectMap); } catch (JsonProcessingException e) { e.printStackTrace(); } } /** * 转换成实体字段 * @param s * @return */ @Override @SuppressWarnings("unchecked") public Map<String, Object> convertToEntityAttribute(String s) { try { return mapper.readValue(s, HashMap.class); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import javax.persistence.AttributeConverter; import java.util.List; /** * @Description List与JSON 映射转换器 * @author coisini * @date Aug 16, 2021 * @Version 1.0 */ 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(); } } @Override @SuppressWarnings("unchecked") public List<Object> convertToEntityAttribute(String s) { try { return mapper.readValue(s, List.class); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
@Convert(converter = MapAndJson.class) private Map<String, Object> test; @Convert(converter = ListAndJson.class) private List<Object> specs;