Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure custom data type TypeHandle for mybatis-plus

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article Xiaobian introduces in detail for you "mybatis-plus how to configure custom data type TypeHandle", the content is detailed, the steps are clear, and the details are handled properly. I hope that this "mybatis-plus how to configure custom data type TypeHandle" article can help you solve your doubts, following the editor's ideas slowly in depth, together to learn new knowledge.

How to configure custom data type TypeHandle1. Background

Mybatis-plus has made comprehensive enhancements on the basis of mybatis, which has greatly improved our development efficiency. Sometimes the entity field type we use does not correspond to the field type created by the database, so we need to configure a custom type handling class to handle the data flow between the code and the database.

two。 Give an example

We have an entity class TestEntity that uses the annotation @ TableName to indicate that the corresponding database table is named test

@ Data@TableName (value = "test") public class TestEntity {private static final long serialVersionUID = 8565214506859404278L; private String id; private String type; private Document content;}

DAO layer object

@ Mapperpublic interface TestDao extends BaseMapper {}

XML file

Document uses org.w3c.dom.Document objects, the field type stored in the database is bytea, and I use postgresql here. Obviously, the data types cannot be matched. Here, you need to write a type handling class for data type conversion.

3.TypeHandle configuration

1. To write TypeHandle, we first need to make clear the respective data types in our code and in the database, write the processing class DocumentTypeHandler inherits BaseTypeHandler, and rewrite four methods:

(1) setNonNullParameter represents the conversion from the data type in the code to the database data type, that is, Document to BLOB type. The basic idea here is to convert Document to String, then to byte stream, and finally to database objects using the setBinaryStream method.

(2) getNullableResult,getNullableResult,getNullableResult means to take data from the database type and convert it to the data type in the code, that is, BLOB to Document type. The basic idea here is the reverse process of the previous step.

@ MappedTypes fills in the data types in our code

@ MappedJdbcTypes filled in the data type in the database

@ 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? 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) {/ / string conversion 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 } return doc;}}

two。 Going back to the entity class configuration, the following is the modified entity class

(1) add autoResultMap = true to the annotation @ TableName to indicate the use of the mapping configuration in xml

(2) add the annotation configuration @ TableField (typeHandler = DocumentTypeHandler.class) to indicate that the content field uses the data type processing class 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. The following is the modified xml configuration

(1) configure jdbcType= "OTHER" in the content field and configure the data processing class typeHandler= "com.aisino.jdbc.ibatis.DocumentTypeHandler"

4. Matters needing attention

(1) when writing TypeHandle classes, it is not possible to inherit BaseTypeHandler, but the reason has not been explored yet.

Custom usage notes for TypeHandler

A custom TypeHandler can be used to automatically convert an attribute when it is inserted into the database and queried. In this case, the attribute of type Map is converted to CLOB and then stored in the database. Due to the complexity of the Map,mp comes with the json converter will lose part of the information.

Type converters can also configure java types and jdbc types through annotations

@ MappedTypes: annotated configuration java type

@ MappedJdbcTypes: annotated configuration jdbc type

Definition:

Use:

Note the @ TableName annotation autoResultMap attribute

@ Data@NoArgsConstructor@TableName (value = "mix_target", autoResultMap = true) public class MixTarget extends Model {@ TableId (value = "id", type = IdType.AUTO) private Long id; / * indicator description * / @ TableField ("description") private String description; / * indicator name * / @ TableField ("name") private String name / * corresponding attribute name * / @ TableField ("property_name") private String propertyName; / * starting point type * / @ TableField ("source_type") private String sourceType / * attribute corresponds to weight list * key attribute name value weight under the specified condition * / @ TableField (value = "weight_list", typeHandler = WeightListTypeHandler.class,jdbcType = JdbcType.CLOB) private Map weightList / * running status * 0 New not running * 1 running * 2 running successfully * 3 running failed * / @ TableField ("status") private Integer status; / * * whether * 1 true * 0 false * / @ TableField ("enable") private Integer enable is available @ TableField ("create_time") private LocalDateTime createTime;} here, this article "how to configure custom data types TypeHandle for mybatis-plus" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 248

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report