前言
将list属性保存进数据库,数据库中的字段属性为text,需要将list转为JSON格式进行保存,查询的时候再将JSON格式转为list集合
实体类
@TableName(value = "t_member",autoResultMap = true)
public class Member implements Serializable {
private static final long serialVersionUID = 1L;
@TableField(typeHandler = JsonStringListTypeHandler.class)
private List<CarInformation> carInformationList;
public List<CarInformation> getCarInformationList() {
return carInformationList;
}
public void setCarInformationList(List<CarInformation> carInformationList) {
this.carInformationList = carInformationList;
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
}
转换类
/**
* 将list集合转为为JSON格式
*
* @author xiangtianlei
* @date 2023/06/29
*/
public class JsonStringListTypeHandler extends BaseTypeHandler<List<CarInformation>> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<CarInformation> parameter, JdbcType jdbcType) throws SQLException {
try {
String jsonString = OBJECT_MAPPER.writeValueAsString(parameter);
ps.setString(i, jsonString);
} catch (JsonProcessingException e) {
throw new SQLException("Error converting CarInformation list to JSON string", e);
}
}
@Override
public List<CarInformation> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parseJsonString(rs.getString(columnName));
}
@Override
public List<CarInformation> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parseJsonString(rs.getString(columnIndex));
}
@Override
public List<CarInformation> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseJsonString(cs.getString(columnIndex));
}
private List<CarInformation> parseJsonString(String jsonString) throws SQLException {
try {
return OBJECT_MAPPER.readValue(jsonString, new TypeReference<List<CarInformation>>() {});
} catch (JsonProcessingException e) {
throw new SQLException("Error converting JSON string to CarInformation list", e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
注意事项
注解:@TableName(value = "t_member",autoResultMap = true)中autoResultMap = true是必须要有的
在需要转为的属性上添加注解:@TableField(typeHandler = JsonStringListTypeHandler.class)