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 realize MyBatis typeAliases and typeHandlers

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to achieve MyBatis typeAliases and typeHandlers". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve MyBatis typeAliases and typeHandlers".

TypeAliases (type alias)

As the name implies, it is an abbreviation of the java type and is convenient to use in other places such as Mapper.

As you can see, the type attribute of the resultMap tag can be matched to the type "com.freecloud.plug.mybatis.entity.User" directly using the alias user, which greatly reduces the writing of fully qualified class names.

You can also use package search to reduce configuration, but you need to add @ Alias annotations to entity classes

@ Data@NoArgsConstructor@AllArgsConstructor@Alias ("user") public class User implements Serializable {/ * * Primary key ID * / private Long id; / * * name * / private String name; / * * Age * / private Integer age;}

Above are some of the types we have customized, and for some basic data types MyBatis has built-in aliases for some basic data types.

They are all case-insensitive, and note that a special naming style is adopted in order to cope with the naming repetition of the original type. As follows:

Type of alias mapping _ bytebyte_longlong_shortshort_intint_integerint_doubledouble_floatfloat_booleanbooleanstringStringbyteBytelongLongshortShortintIntegerintegerIntegerdoubleDoublefloatFloatbooleanBooleandateDatedecimalBigDecimalbigdecimalBigDecimalobjectObjectmapMaphashmapHashMaplistListarraylistArrayListcollectionCollectioniteratorIteratortypeHandlers (type handler)

Because the java type is not one-to-one corresponding to the JDBC type of the database (such as String and varchar, char, text), when we convert the java object into the database value, and the database value into the java object, we need to go through a certain conversion, and the conversion in these two directions will use TypeHandler.

When we use it normally, we don't do any configuration, so why can the String property in the object be converted into the varchar field in the database?

This is because MyBatis already has a lot of built-in TypeHandler (under the org.apache.ibatis.type package), they are all registered in TypeHandlerRegistry, and they all inherit the abstract class BaseTypeHandler, and generics are the java data types to be processed.

That's why most types don't need us to deal with. When we query data and manipulate data, when we do data type conversion, the corresponding TypeHandler method is automatically called.

If we want to customize some type conversion rules, or deal with some special types, such as supporting json types after mysql 5.7, using a field to store multiple foreign keys ID for "," separation, or supporting field enumeration types, automatic conversion, and so on.

Let's customize a TypeHandler to implement a simple json type field that supports mysql 5.7.

First of all, like the system-defined TypeHandlerg, it inherits the abstract class BaseTypeHandler. There are four abstract methods that must be implemented, which we divide into two categories:

The set method is converted from java type to JDBC type, and the get method is converted from JDBC type to java type.

Here, the Json type data in the database is converted into JSON objects in hutool.

Write a custom typeHander

Package com.freecloud.plug.mybatis.type;import cn.hutool.json.JSON;import cn.hutool.json.JSONUtil;import com.freecloud.common.LoggerUtil;import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException / * * Note: you need to use mysql-connector 5.1.40 or above to solve the mysql json format garbled problem * @ Author: maomao * @ Date: 2021-04-09 11:16 * / public class JsonTypeHandler extends BaseTypeHandler {@ Override public void setNonNullParameter (PreparedStatement ps, int I, JSON parameter, JdbcType jdbcType) throws SQLException {LoggerUtil.printThread ("java-> jdbc type"); ps.setString (iForce parameter.toString ()) } @ Override public JSON getNullableResult (ResultSet rs, String columnName) throws SQLException {LoggerUtil.printThread ("jdbc-> java type is obtained by column name"); return JSONUtil.parse (rs.getString (columnName));} @ Override public JSON getNullableResult (ResultSet rs, int columnIndex) throws SQLException {LoggerUtil.printThread ("jdbc-> java type is obtained by ordinal number"); return JSONUtil.parse (rs.getString (columnIndex)) } @ Override public JSON getNullableResult (CallableStatement cs, int columnIndex) throws SQLException {LoggerUtil.printThread ("jdbc-> java type stored procedure usage"); return JSONUtil.parse (cs.getString (columnIndex));}}

Register in the mybatis-config.xml file

Specify on the fields we need to use

Prepare data

# # mybatis Test typeHander added json conversion CREATE TABLE `mybatis_ json` (`id` int (5) NOT NULL, `name` varchar (255) COLLATE utf8mb4_bin DEFAULT NULL, `json` json DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;insert into mybatis_json values.

Instance object

@ Data@ToStringpublic class MyBatisJson implements Serializable {/ * * primary key ID * / private Long id; / * * name * / private String name; / * * json * / private JSON json;}

Unit test:

/ * Test to get data of type json, convert * / @ Testpublic void testJsonTypeHander () {SqlSession sqlSession = sqlSessionFactory.openSession (); try {MyBatisJsonMapper mapper = sqlSession.getMapper (MyBatisJsonMapper.class); MyBatisJson myBatisJson = mapper.byId (1L); LoggerUtil.printThread (myBatisJson.toString ());} finally {sqlSession.close ();}}

/ / add @ Testpublic void testSaveJsonTypeHander () {SqlSession sqlSession = sqlSessionFactory.openSession (); try {MyBatisJsonMapper mapper = sqlSession.getMapper (MyBatisJsonMapper.class); MyBatisJson myBatisJson = new MyBatisJson (); myBatisJson.setId (1001L); myBatisJson.setName ("name:" + DateUtil.now ()); myBatisJson.setJson ("{\" remark\ ":\" + DateUtil.now () + "\"} ") Mapper.save (myBatisJson); sqlSession.commit (); LoggerUtil.printThread (myBatisJson.toString ());} finally {sqlSession.close ();}}

Thank you for your reading, the above is the content of "how to achieve MyBatis typeAliases and typeHandlers", after the study of this article, I believe you have a deeper understanding of how to achieve MyBatis typeAliases and typeHandlers, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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: 0

*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