项目中有系统IP字段,现将string转List存入数据库,每个功能块持久层实现方法不一样(分为jpa和mp)
jpa:
@Convert(converter = JpaConverterListJson.class) private List<String> hostIp; public class JpaConverterListJson implements AttributeConverter<Object, String> { @Override public String convertToDatabaseColumn(Object o) { return JSON.toJSONString(o); } @Override public Object convertToEntityAttribute(String s) { //兼容历史数据 if (!JSONUtil.isJson(s)) { return new JSONArray(Arrays.asList(s)); } return JSON.parseArray(s); }
ps:貌似@Lob也可以直接保存,没试过
mp:
@TableField(typeHandler = ArrayTypeHandler.class) private List<String> hostIp;
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ArrayTypeHandler extends BaseTypeHandler<List> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, List list, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i, JSON.toJSONString(list));
}
@Override
public List getNullableResult(ResultSet resultSet, String s) throws SQLException {
//兼容历史数据
if (!JSONUtil.isJson(resultSet.getString(s))) {
return new JSONArray(Arrays.asList(resultSet.getString(s)));
}
return JSON.parseArray(resultSet.getString(s));
}
@Override
public List getNullableResult(ResultSet resultSet, int i) throws SQLException {
JSONArray jsonArray = JSONArray.parseArray(resultSet.getString(i));
return jsonArray;
}
@Override
public List getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
JSONArray jsonArray = JSONArray.parseArray(callableStatement.getString(i));
return jsonArray;
}
//单这样查询获取不到,mp查询跟增改使用的ResultMap是不同的 //注解的typeHandler只生效于insert和update,要生效select必须@TableName(autoResultMap=true)
//但在自定义查询中添加了autoResultMap也没有用,还要在配置里加上map,查询结果指向它
<resultMap id="BaseResultMap" type="com.jk.cmdb.setting.entity.CmdbPc">
<result column="host_ip" property="hostIp"
typeHandler="com.jk.moinc.framework.ArrayTypeHandler"/>
</resultMap>
https://blog.csdn.net/sinat_38073073/article/details/110136015
https://www.jianshu.com/p/1fbaff7fb187
https://github.com/baomidou/mybatis-plus/issues/357
jpa:
https://greenhtml.com/archives/153.html
https://blog.csdn.net/losfog/article/details/88046161
ps:如果是自定义的数组字段,是无法直接存入数据库也无法通过上述方式,那么存储转json字符串,取出转jsonArray