本文小编为大家详细介绍“mybatis-plus怎么配置自定义数据类型TypeHandle”,内容详细,步骤清晰,细节处理妥当,希望这篇“mybatis-plus怎么配置自定义数据类型TypeHandle”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
mybatis-plus在mybatis的基础的上,做了全面增强功能,极大的提高了我们的开发效率。有时候我们使用的实体字段类型,与数据库创建的字段类型无法对应上,这时候就需要配之自定义的类型处理类,来处理代码和数据库之间的数据流转。
我们有个实体类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<TestEntity> {
}
XML文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aisino.dao.TestDao">
<resultMap type="com.aisino.entity.TestEntity" id="testMap">
<result property="id" column="id"/>
<result property="type" column="name"/>
<result property="content" column="content"/>
</resultMap>
</mapper>
其中Document使用的是org.w3c.dom.Document对象,数据库存储的字段类型为bytea,我这里使用的是postgresql,显然数据类型无法匹配,这里需要编写类型处理类进行数据类型转换。
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”
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aisino.dao.TestDao">
<resultMap type="com.aisino.entity.TestEntity" id="testMap">
<result property="id" column="id"/>
<result property="type" column="name"/>
<result property="content" column="content" jdbcType="OTHER" typeHandler="com.aisino.jdbc.ibatis.DocumentTypeHandler"/>
</resultMap>
</mapper>
4.注意事项
(1)编写TypeHandle类时候,继承BaseTypeHandler<Document>试过不行,原因暂未深究。
(2)实体类的注解@TableField(typeHandler = DocumentTypeHandler.class)与xml配置的处理类路径typeHandler="com.aisino.jdbc.ibatis.DocumentTypeHandler"缺一不可,因为看过网上说只配置注解即可,我试了不行,原因暂未深究。
可通过自定义的TypeHandler实现某个属性在插入数据库以及查询时的自动转换,本例中是要将Map类型的属性转化成CLOB,然后存入数据库。由于是复杂的Map,mp自带的json转换器会丢失部分信息。
@MappedTypes
:注解配置 java 类型
@MappedJdbcTypes
:注解配置 jdbc 类型
定义:
@Slf4j
@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class WeightListTypeHandler extends AbstractJsonTypeHandler<Object> {
private static Gson gson = new Gson();
private final Class<?> type;
public WeightListTypeHandler(Class<?> type) {
if (log.isTraceEnabled()) {
log.trace("WeightListTypeHandler(" + type + ")");
}
Assert.notNull(type, "Type argument cannot be null");
this.type = type;
}
@Override
protected Object parse(String json) {
Type type1 = new TypeToken<Map<String, List<WeightItem>>>(){}.getType();
return gson.fromJson(json, type1);
}
@Override
protected String toJson(Object obj) {
return gson.toJson(obj);
}
public static void setGson(Gson gson) {
Assert.notNull(gson, "Gson should not be null");
WeightListTypeHandler.gson = gson;
}
}
使用:
注意@TableName 注解 autoResultMap 属性
@Data
@NoArgsConstructor
@TableName(value = "mix_target",autoResultMap = true)
public class MixTarget extends Model<MixTarget> {
@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<String, List<WeightItem>> 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;
}
读到这里,这篇“mybatis-plus怎么配置自定义数据类型TypeHandle”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。