处理 long类型值为小于int.max 数据格式错误问题
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
package org.jiayunet.config;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
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 java.sql.CallableStatement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* List<Long> 类型的 JSON TypeHandler
|
||||
* <p>解决 JacksonTypeHandler 反序列化 JSON 数组时将小数字解析为 Integer 的问题</p>
|
||||
*
|
||||
* @author zk
|
||||
*/
|
||||
@MappedTypes(List.class)
|
||||
@MappedJdbcTypes(JdbcType.VARCHAR)
|
||||
public class LongListTypeHandler extends BaseTypeHandler<List<Long>> {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final TypeReference<List<Long>> TYPE_REF = new TypeReference<>() {};
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i, List<Long> parameter, JdbcType jdbcType) throws SQLException {
|
||||
try {
|
||||
ps.setString(i, MAPPER.writeValueAsString(parameter));
|
||||
} catch (Exception e) {
|
||||
throw new SQLException("序列化 List<Long> 失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Long> getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
return parse(rs.getString(columnName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Long> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return parse(rs.getString(columnIndex));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Long> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
return parse(cs.getString(columnIndex));
|
||||
}
|
||||
|
||||
private List<Long> parse(String json) throws SQLException {
|
||||
if (json == null || json.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readValue(json, TYPE_REF);
|
||||
} catch (Exception e) {
|
||||
throw new SQLException("反序列化 List<Long> 失败: " + json, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user