问题说明
自定义DataTypeTypeHandler
package com.xjhqre.iot.mybatisConfig;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.alibaba.fastjson2.JSON;
import com.xjhqre.iot.domain.model.DataType;
public class DataTypeTypeHandler extends BaseTypeHandler<DataType> {
/**
* @param ps
* SQL预编译对象
* @param i
* 需要赋值的索引位置(相当于在JDBC中对占位符的位置进行赋值)
* @param parameter
* 索引位置i需要赋的值(原本要给这个位置赋的值,在setNonNullParameter方法中主要解决的问题就是将这个自定义类型变成数据库认识的类型)
* @param jdbcType
* jdbc的类型
* @throws SQLException
*/
@Override
public void setNonNullParameter(PreparedStatement ps, int i, DataType parameter, JdbcType jdbcType)
throws SQLException {
if (parameter == null) {
ps.setString(i, null);
return;
}
ps.setString(i, JSON.toJSONString(parameter));
}
@Override
public DataType getNullableResult(ResultSet rs, String columnName) throws SQLException {
return JSON.parseObject(rs.getString(columnName), DataType.class);
}
@Override
public DataType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return JSON.parseObject(rs.getString(columnIndex), DataType.class);
}
@Override
public DataType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return JSON.parseObject(cs.getString(columnIndex), DataType.class);
}
}
ThingModel实体类
package com.xjhqre.iot.domain.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.xjhqre.common.base.BaseEntity;
import com.xjhqre.iot.domain.model.DataType;
import com.xjhqre.iot.mybatisConfig.DataTypeTypeHandler;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
@TableName(value = "thing_model", autoResultMap = true)
public class ThingModel extends BaseEntity {
private static final long serialVersionUID = 1L;
// ...
@ApiModelProperty(value = "数据定义")
@TableField(typeHandler = DataTypeTypeHandler.class)
private DataType dataType;
@ApiModelProperty(value = "入参定义")
@TableField(typeHandler = DataTypeTypeHandler.class)
private DataType inputParam;
@ApiModelProperty(value = "出参定义")
@TableField(typeHandler = DataTypeTypeHandler.class)
private DataType outputParam;
// ...
}
setNonNullParameter 方法会在插入数据库时,将类型为 DataType 的数据转为 JSON 格式存入
getNullableResult 方法则是在读取数据库时,将 JSON 格式转为 DataType 类型
结果发现,使用 mybatis-plus 自带的查询方法可以转换成功,但是使用 xml 文件编写 sql 查询就会转换失败
解决方法
在 application.yml 配置文件中设置自定义 typeHandler 的目录的引用地址
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
id-type: ASSIGN_ID
# 设置自定义 typeHandler 目录
type-handlers-package: com.xjhqre.iot.mybatisConfig