Spring Boot MyBatis 将 PostgreSQL 数组转为 Java List
MyBatis PostgreSQL Spring Boot About 2,225 words类型处理器
@MappedJdbcTypes({JdbcType.ARRAY})
@MappedTypes({Object.class})
public class ListTypeHandler extends BaseTypeHandler<List<?>> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<?> parameter, JdbcType jdbcType) throws SQLException {
Connection conn = ps.getConnection();
Array array = conn.createArrayOf(jdbcType.name(), parameter.toArray());
ps.setArray(i, array);
array.free();
}
@Override
public List<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return extractArray(rs.getArray(columnName));
}
@Override
public List<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return extractArray(rs.getArray(columnIndex));
}
@Override
public List<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return extractArray(cs.getArray(columnIndex));
}
protected List<?> extractArray(Array array) throws SQLException {
if (array == null) {
return null;
}
Object javaArray = array.getArray();
array.free();
return new ArrayList<>(Arrays.asList((Object[]) javaArray));
}
}
YAML 配置
指定类型处理器这个类所在的包的全路径。
mybatis:
type-handlers-package: z.note.lite.config.mybatis
使用
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="z.note.lite.mapper.api.PostMgmtMapper">
<resultMap id="base" type="z.note.lite.entity.Post">
<result column="topics" property="topics" typeHandler="z.note.lite.config.mybatis.ListTypeHandler" />
<result column="images" property="images" typeHandler="z.note.lite.config.mybatis.ListTypeHandler" />
</resultMap>
</mapper>
@Select
@Mapper
public interface PostMgmtMapper {
@Select("select * from post where id = #{id}")
@Results({
@Result(column = "topics", property = "topics", typeHandler = ListTypeHandler.class),
@Result(column = "images", property = "images", typeHandler = ListTypeHandler.class)
})
Post findById(Integer id);
}
Views: 893 · Posted: 2024-05-20
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...