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 customize global TypeHander in Mybatis

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is to share with you about how to customize the global TypeHander in Mybatis. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

1. First create List's TypeHanderpublic class ListTypeHandler extends BaseTypeHandler {@ Override public void setNonNullParameter (PreparedStatement ps, int I, List parameter, JdbcType jdbcType) throws SQLException {if (jdbcType = = null) {ps.setString (I, StringUtils.collectionToCommaDelimitedString (parameter));} else {ps.setObject (I, parameter, jdbcType.TYPE_CODE) } @ Override public List getNullableResult (ResultSet rs, String columnName) throws SQLException {String s = rs.getString (columnName); return s==null? Null: new ArrayList (Arrays.asList (s.split (","));} @ Override public List getNullableResult (ResultSet rs, int columnIndex) throws SQLException {String s = rs.getString (columnIndex); return s==null? Null: new ArrayList (Arrays.asList (s.split (","));} @ Override public List getNullableResult (CallableStatement cs, int columnIndex) throws SQLException {String s = cs.getString (columnIndex); return s==null? Null: new ArrayList (Arrays.asList (s.split (",));}}

First of all, inherit BaseTypeHandler and specify its generic parameters as the java type we need to convert. BaseTypeHandler uses the template method pattern, encapsulating a lot of null judgment and exception handling. Just to be clear: the type converter here does not specify a specific jdbcType, so mybatis automatically determines that it matches the converter when the java type is List.

two。 Then register with Mybatis's TypeHandlerRegistry

Registration to TypeHandlerRegistry is for global customization. If you do not register, you need the resultMap in Mapper,xml to specify the typeHander, such as:

The idea of registration is to directly remove the TypeHandlerRegistry from the spring container when the bean is loaded, and then register our custom converter:

/ * @ author chenzhicong * @ time, 2019-8-13 22:19 * @ description * / @ Componentpublic class CustomTypeHandlerParser implements ApplicationContextAware {@ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {/ / get sqlSessionFactory SqlSessionFactory sqlSessionFactory = applicationContext.getBean (SqlSessionFactory.class) from the spring container; / / get the typeHandler registry TypeHandlerRegistry typeHandlerRegistry = sqlSessionFactory.getConfiguration (). GetTypeHandlerRegistry () / / register List's typeHandler typeHandlerRegistry.register (List.class, ListTypeHandler.class);}} III. Test @ Test public void test () {UserJpaTest userJpaTest = new UserJpaTest (); List list = new ArrayList (); list.add ("phoneNumber1"); list.add ("phoneNumber2"); userJpaTest.setPhoneNumber (list); userJpaTestMapper.insert (userJpaTest);} IV.

As you can see, the collection has been converted to a comma-separated string in the database.

5. Advanced-create an enumerated TypeHandler

TypeHander is also often used in the conversion strategy between enumerations and database strings. In business, we usually enumerate three variables, one is the display character for the front end, one is the character stored in the database, and the other is our character in the java system. In order for the database to recognize only the characters we have stored in the database, and convert the characters in the database to the enumerations we want. We can use custom converters to facilitate implementation. The following process is described below:

First of all, we can abstract all enumerations into an interface. As follows, we abstract all the EntityEnumIFace interfaces enumerated as an interface enumeration, and the getDbCode method of the interface is the database string to be converted. We use this converter to handle the conversion of this kind of enumeration abstraction:

Public final class EntityEnumIFaceHandler extends BaseTypeHandler {private Class type; public EntityEnumIFaceHandler (Class type) {if (null = = type) {throw new IllegalArgumentException ("type parameter cannot be empty");} else {this.type = type } @ Override public void setNonNullParameter (PreparedStatement preparedStatement, int I, T t, JdbcType jdbcType) throws SQLException {if (jdbcType = = null) {preparedStatement.setString (I, ((EntityEnumIFace) t) .getDbCode ());} else {preparedStatement.setObject (I, ((EntityEnumIFace) t) .getDbCode (), jdbcType.TYPE_CODE) } @ Override public T getNullableResult (ResultSet resultSet, String s) throws SQLException {String value = resultSet.getString (s); return value = = null? Null: valueOf (this.type, value);} @ Override public T getNullableResult (ResultSet resultSet, int I) throws SQLException {String value = resultSet.getString (I); return value = = null? Null: valueOf (this.type, value);} @ Override public T getNullableResult (CallableStatement callableStatement, int I) throws SQLException {String value = callableStatement.getString (I); return value = = null? Null: valueOf (this.type, value);} private static E valueOf (Class enumClass, String dbCode) {E [] enumConstants = enumClass.getEnumConstants (); if (null! = enumConstants) {for (E e: enumConstants) {if (e.getDbCode (). Equals (dbCode)) {return e } throw new BusinessException ("ENUM_NOT_EXIST", enumClass.getSimpleName () + "not in enumeration" + dbCode, false);}}

You may wonder why there is no parametric constructor for the previously defined converter instantiation, but the parameterized constructor is defined here. What is the process of instantiation? Don't worry, we'll look at it later. Here we register it to the container first. How can we register it to the container? Here, you can scan the specified package path and get all enumerated class objects before registering with mybatis with typeHandlerRegistry.register, such as:

Try {Set

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

Internet Technology

Wechat

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

12
Report