做网站架构,莞城网站建设公司,app推广赚钱平台,建站公司是什么困扰了好几个小时。。。
场景#xff1a;mybatisplus从数据库取数据#xff0c;只是用了最基础的 LambdaQueryWrapper 来查询#xff0c;实体类如下。
TableField(typeHandler JacksonTypeHandler.class)
private SetLong ids;
得到的Set数据却是SetInteger…困扰了好几个小时。。。
场景mybatisplus从数据库取数据只是用了最基础的 LambdaQueryWrapper 来查询实体类如下。
TableField(typeHandler JacksonTypeHandler.class)
private SetLong ids;
得到的Set数据却是SetInteger类型。离谱。。。
后来查了资料才发现 Json序列化时Josn串是没有Long类型的而且反转回来也是Object接收如果数字小于Interger的最大值给转成了Integer
既然是这么个问题那么我们可以自定义转换类 typeHandler 参数
package co.utils;import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;MappedJdbcTypes(JdbcType.VARCHAR) // 数据库中该字段存储的类型
MappedTypes(List.class) // 需要转换的对象
public class ListInteger2ListLongTypeHandler extends BaseTypeHandlerListLong {private static final ObjectMapper objectMapper new ObjectMapper();Overridepublic void setNonNullParameter(PreparedStatement ps, int i, ListLong parameter, JdbcType jdbcType) throws SQLException {ps.setObject(i, JSON.toJSONString(parameter));}Overridepublic ListLong getNullableResult(ResultSet rs, String columnName) throws SQLException {return getLongs(rs.getString(columnName));}Overridepublic ListLong getNullableResult(ResultSet rs, int columnIndex) throws SQLException {return getLongs(rs.getString(columnIndex));}Overridepublic ListLong getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {return getLongs(cs.getString(columnIndex));}private ListLong getLongs(String value) {if (StringUtils.hasText(value)) {try {CollectionType type objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, Long.class);return objectMapper.readValue(value, type);//ListLong longs JsonUtil.parseArray(value, Long.class);} catch (JsonProcessingException e) {e.printStackTrace();}}return null;}
}
开发中尽量不要乱用一些对象属性转换工具。 如果不想定义一个类的话可以试试这种方法
ListLong ids1 JSON.parseArray(JSON.toJSONString(ids), Long.class);
将ids先转成字符串然后再通过JSON转成数组 完~ 参考JSON序列化导致Long类型被搞成Integer怎么解决_编程网
Java Number类