feat:
1. add jsonb handler
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
package org.springblade.common.handler;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
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 org.postgresql.util.PGobject;
|
||||
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 用于 PostgreSQL JSONB 与 Java 对象(如 List<Map>、Map 等)的双向转换
|
||||
*/
|
||||
@MappedJdbcTypes(JdbcType.OTHER)
|
||||
@MappedTypes({List.class, Map.class})
|
||||
public class PgJsonbTypeHandler extends BaseTypeHandler<Object> {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
|
||||
PGobject jsonObject = new PGobject();
|
||||
jsonObject.setType("jsonb");
|
||||
try {
|
||||
jsonObject.setValue(objectMapper.writeValueAsString(parameter));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new SQLException("Error converting object to JSON", e);
|
||||
}
|
||||
ps.setObject(i, jsonObject);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
return parseJson(rs.getString(columnName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return parseJson(rs.getString(columnIndex));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
return parseJson(cs.getString(columnIndex));
|
||||
}
|
||||
|
||||
private Object parseJson(String json) throws SQLException {
|
||||
if (json == null || json.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// 根据实际泛型类型反序列化(此处简化为返回 Object)
|
||||
// 更精确的做法是使用 ParameterizedType,但 MyBatis 不支持泛型擦除后的还原
|
||||
// 所以通常在 Service 层做二次转换,或使用 JsonNode
|
||||
return objectMapper.readValue(json, Object.class);
|
||||
} catch (Exception e) {
|
||||
throw new SQLException("Error parsing JSON", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user