如何配置自定义数据类型TypeHandle
1.背景
mybatis-plus在mybatis的基础的上,做了全面增强功能,极大的提高了我们的开发效率。有时候我们使用的实体字段类型,与数据库创建的字段类型无法对应上,这时候就需要配之自定义的类型处理类,来处理代码和数据库之间的数据流转。
2.举例
我们有个实体类TestEntity,使用注解@TableName表示对应数据库表名为test
@Data
@TableName(value = "test")
public class TestEntity{
  private static final long serialVersionUID = 8565214506859404278L;
  private String id;
  private String type;
  private Document content;
}
 
DAO层对象
@Mapper
public interface TestDao extends BaseMapper {
} 
 
XML文件
其中Document使用的是org.w3c.dom.Document对象,数据库存储的字段类型为bytea,我这里使用的是postgresql,显然数据类型无法匹配,这里需要编写类型处理类进行数据类型转换。
3.TypeHandle配置
1.编写TypeHandle,首先需要明确我们代码中和数据库中各自的数据类型,编写处理类DocumentTypeHandler继承BaseTypeHandler,并重写4个方法:
(1)setNonNullParameter表示从代码中的数据类型转换成数据库数据类型,即Document转为BLOB类型。这里的基本思路就是将Document转为String再转为字节流,最后利用setBinaryStream方法转为数据库对象。
(2)getNullableResult,getNullableResult,getNullableResult表示从数据库类型中获取数据并转换为代码中的数据类型,即BLOB转为Document类型。这里的基本思路就是上一步的逆过程。
	- @MappedTypes中填写的是我们代码中的数据类型
- @MappedJdbcTypes中填写的是数据库中的数据类型
@MappedTypes(Document.class)
@MappedJdbcTypes(JdbcType.BLOB)
public class DocumentTypeHandler extends BaseTypeHandler {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
        String docStr = docToString((org.w3c.dom.Document) parameter);
        InputStream in = new ByteArrayInputStream(docStr.getBytes());
        ps.setBinaryStream(i, in);
    }
    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        byte[] bytes = rs.getBytes(columnName);
        return !rs.wasNull() && bytes != null ? stringToDoc(new String(bytes)) : null;
    }
    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        byte[] bytes = rs.getBytes(columnIndex);
        return !rs.wasNull() && bytes != null ? stringToDoc(new String(bytes)) : null;
    }
    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        byte[] bytes = cs.getBytes(columnIndex);
        return !cs.wasNull() && bytes != null ? stringToDoc(new String(bytes)) : null;
    }
    public static String docToString(Document doc) {
        // XML转字符串
        String xmlStr = "";
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.setOutputProperty("encoding", "UTF-8");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            t.transform(new DOMSource(doc), new StreamResult(bos));
            xmlStr = bos.toString();
        } catch (TransformerConfigurationException e) {
            // TODO
            e.printStackTrace();
        } catch (TransformerException e) {
            // TODO
            e.printStackTrace();
        }
        return xmlStr;
    }
    public static Document stringToDoc(String xmlStr) {
        //字符串转XML
        Document doc = null;
        try {
            xmlStr = new String(xmlStr.getBytes(), "UTF-8");
            StringReader sr = new StringReader(xmlStr);
            InputSource is = new InputSource(sr);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = factory.newDocumentBuilder();
            doc = builder.parse(is);
        } catch (ParserConfigurationException e) {
            // TODO
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO
            e.printStackTrace();
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
        return doc;
    }
}
 
2.回到实体类配置,以下是修改后的实体类
(1)在注解@TableName中增加autoResultMap = true表示使用xml中的映射配置
(2)增加注解配置@TableField(typeHandler = DocumentTypeHandler.class)表示content字段使用数据类型处理类DocumentTypeHandler.class 
@Data
@TableName(value = "test",autoResultMap = true)
public class TestEntity{
  private static final long serialVersionUID = 8565214506859404278L;
  private String id;
  private String type;
  @TableField(typeHandler = DocumentTypeHandler.class)
  private Document content;
}
 
3.以下是修改后的xml配置
(1)content字段配置jdbcType=“OTHER”,配置数据处理类typeHandler=“com.aisino.jdbc.ibatis.DocumentTypeHandler”
 4.注意事项
(1)编写TypeHandle类时候,继承BaseTypeHandler试过不行,原因暂未深究。
(2)实体类的注解@TableField(typeHandler = DocumentTypeHandler.class)与xml配置的处理类路径typeHandler="com.aisino.jdbc.ibatis.DocumentTypeHandler"缺一不可,因为看过网上说只配置注解即可,我试了不行,原因暂未深究。 
自定义TypeHandler的使用笔记
可通过自定义的TypeHandler实现某个属性在插入数据库以及查询时的自动转换,本例中是要将Map类型的属性转化成CLOB,然后存入数据库。由于是复杂的Map,mp自带的json转换器会丢失部分信息。
类型转换器还可以通过注解配置java类型和jdbc类型
@MappedTypes:注解配置 java 类型
@MappedJdbcTypes:注解配置 jdbc 类型
定义:
@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class WeightListTypeHandler  extends AbstractJsonTypeHandler
 
使用:
注意@TableName 注解 autoResultMap 属性
@Data
@NoArgsConstructor
@TableName(value = "mix_target",autoResultMap = true)
public class MixTarget extends Model {
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    /**
     *指标描述
     */
    @TableField("description")
    private String description;
    /**
     * 指标名
     */
    @TableField("name")
    private String name;
    /**
     * 对应属性名
     */
    @TableField("property_name")
    private String propertyName;
    /**
     * 起始点类型
     */
    @TableField("source_type")
    private String sourceType;
    /**
     * 属性对应权值列表
     * key 属性名 value指定条件下的权值
     */
    @TableField(value = "weight_list",typeHandler = WeightListTypeHandler.class,jdbcType = JdbcType.CLOB)
    private Map> weightList;
    /**
     * 运行状态
     * 0 新建未运行
     * 1 运行中
     * 2 已运行 成功
     * 3 已运行 失败
     */
    @TableField("status")
    private Integer status;
    /**
     * 是否可用
     * 1 true
     * 0 false
     */
    @TableField("enable")
    private Integer enable;
    @TableField("create_time")
    private LocalDateTime createTime;
}