- mybatis-plus中json字段的使用
在DO类上加@TableName(value = "t_user", autoResultMap = true)
在json字段上加@TableField(typeHandler = FastjsonTypeHandler.class)
如下
@Data
@Accessors(chain = true)
@TableName(value = "t_user", autoResultMap = true)
public class UserDO{
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField(typeHandler = FastjsonTypeHandler.class)
private List<Long> friendIds;
}
在从数据库取出时,如果json数组中的值小于Integer.MAX_VALUE,则反序列化时会转成List<Integer>类型。
list.contains(longvalue),返回false。
list.remove(longvalue),报错。
不要用FastjsonTypeHandler
,用自定义TypeHandler
@MappedJdbcTypes(JdbcType.VARCHAR) // 数据库中该字段存储的类型
@MappedTypes(List.class) // 需要转换的对象
public class ListInteger2ListLongTypeHandler extends BaseTypeHandler<List<Long>> {
private static ObjectMapper objectMapper = new ObjectMapper();
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
ps.setObject(i, JSON.toJSONString(parameter));
}
@Override
public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return getLongs(rs.getString(columnName));
}
@Override
public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return getLongs(rs.getString(columnIndex));
}
@Override
public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return getLongs(cs.getString(columnIndex));
}
private List<Long> getLongs(String value) {
if (StringUtils.hasText(value)) {
try {
CollectionType type = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Long.class);
return objectMapper.readValue(value, type);
//List<Long> longs = JsonUtil.parseArray(value, Long.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
return null;
}
}