大坑!List<Long>json数组反序列化时被偷偷转成List<Integer>

  • 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;
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容