mybatis 自定义转换器 ListTypeHandler Published on Dec 7, 2022 in Java随笔 with 0 comment mybatis 自定义转换器 ListTypeHandler 实现存库 list->string 读库 string->list ```java package com.jeesite.modules.handler; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.jeesite.common.lang.ObjectUtils; import com.jeesite.common.lang.StringUtils; 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.ArrayList; import java.util.List; /** * @author liuxin * @version 1.0 * @date 2022/8/23 12:25 */ @MappedJdbcTypes(JdbcType.VARCHAR) @MappedTypes({List.class}) public abstract class ListTypeHandler extends BaseTypeHandler> { @Override public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException { String content = ObjectUtils.isEmpty(parameter) ? null : JSON.toJSONString(parameter); ps.setString(i, content); } @Override public List getNullableResult(ResultSet rs, String columnName) throws SQLException { return this.getListByJsonArrayString(rs.getString(columnName)); } @Override public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return this.getListByJsonArrayString(rs.getString(columnIndex)); } @Override public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return this.getListByJsonArrayString(cs.getString(columnIndex)); } private List getListByJsonArrayString(String content) { return StringUtils.isBlank(content) ? new ArrayList<>() : JSON.parseObject(content, this.specificType()); } /** * 具体类型,由子类提供 * * @return 具体类型 */ protected abstract TypeReference> specificType(); } ``` ```java Java 泛型 如果在 ListTypeHandler 类中直接提供 TypeReference> 这种类型,那就等效于TypeReference> 这种类型,后续 fastjson 在转换时无法确定具体的 Java 类型,转换后的类型最终就会是 List ;同理,如果使用 Jackson 作为 JSON 转换工具,不确定具体类型时,最总会被转换为LinkedHashMap 类型,都需要再使用 TypeReference 来转换一次。 自定义TypeHandler的使用笔记 可通过自定义的TypeHandler实现某个属性在插入数据库以及查询时的自动转换。 ``` ```java package com.jeesite.modules.handler; /** * @author liuxin * @version 1.0 * @date 2022/8/23 12:33 */ import com.alibaba.fastjson.TypeReference; import com.pdd.pop.sdk.http.api.pop.response.PddGoodsListGetResponse; import java.util.List; public class SkuListItemSpecDetailsTypeHandler extends ListTypeHandler { @Override protected TypeReference> specificType() { return new TypeReference>() { }; } } ``` 实体类上直接用注解: ```java typeHandler = ListTypeHandler.class, javaType = PddGoodsListGetResponse.GoodsListGetResponseGoodsListItemSkuListItemSpecDetailsItem.class ``` mapper.xml ```xml SELECT ${sqlMap.column.toSql()} FROM ${sqlMap.table.toSql()} ${sqlMap.where.toSql()} ORDER BY ${sqlMap.order.toSql()} ``` 本文由 admin 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。