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

What is the method of mybatis TypeHandler injecting spring dependencies

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what is the method of mybatis TypeHandler injecting spring dependency". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the method of mybatis TypeHandler injecting spring dependency".

Dependency solution of TypeHandler injection spring

When mybatis wants to implement business functions by writing a custom handler, when the handler is created by default, it is not within the management scope of spring, so if you use @ Autowired injection in handler, you will report npe.

It can be solved through the above way.

Mybatis extensions: custom TypeHandler

Many default type handlers are defined in Mybatis to convert the value in the sql statement to the type of JDBC and the value in the result set to the value of the field type. For more information, please see the default TypeHandler on the official website. But sometimes when we don't want to use the TypeHandler on the official website, the custom TypeHandler comes in handy.

1. Write a custom TypeHandler

Add @ MappedJdbcTypes (JdbcType.VARCHAR) annotation to the custom class, and the JdbcType.Varchar in parentheses needs to be replaced

The default JDBC type, and then let this class inherit BaseHandler, the generic type String describes instead of the String type, and then overrides the method

Just deal with it. Each method must return a value. If no value is returned, nothing will be returned by default. As a result, the inserted value is null, and all the values obtained are null.

Package javaDIYFree.typeHandler;import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;import org.apache.ibatis.type.MappedJdbcTypes;import sun.security.provider.MD5;import java.sql.CallableStatement;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException / * * @ author Hearts * @ date 2019-4-17 * @ desc * / @ MappedJdbcTypes (JdbcType.VARCHAR) / / default JDBC type to be replaced Generic type String description replaces String type public class VarcharTypeHandler extends BaseTypeHandler {/ * to process the set value * @ param preparedStatement * @ param I * @ param s * @ param jdbcType * @ throws SQLException * / @ Override public void setNonNullParameter (PreparedStatement preparedStatement, int I, String s) JdbcType jdbcType) throws SQLException {/ / I added a string preparedStatement.setString to the string passed in (iMagazine + ">") } / * extends the operation of getting the value. The column name is * @ param resultSet * @ param s * @ return * @ throws SQLException * / @ Override public String getNullableResult (ResultSet resultSet, String s) throws SQLException {return resultSet.getString (s) } / * extends the operation of getting values, indexing method: * @ param resultSet * @ param I * @ return * @ throws SQLException * / @ Override public String getNullableResult (ResultSet resultSet, int I) throws SQLException {return resultSet.getString (I) * @ param callableStatement * @ param I * @ return * @ throws SQLException * / @ Override public String getNullableResult (CallableStatement callableStatement, int I) throws SQLException {return callableStatement.getString (I);}} 2. Configure TypeHandler

There are two ways to configure it. One is to configure custom TypeHandler directly when configuring SqlSessionFactoryBean, but this method is not commonly used, because it means that all Varchar operations use custom TypeHandler. Generally, we only need to customize a certain field in a certain table. At this time, we configure it in the second way.

The first configuration mode

@ Bean public SqlSessionFactoryBean createSqlSessionFactoryBean (DruidDataSource druidDataSource) {final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean (); try {/ / configure the data source sqlSessionFactoryBean.setDataSource (druidDataSource); / / configure the location of the mapper file sqlSessionFactoryBean.setMapperLocations (new PathMatchingResourcePatternResolver () .getResources ("classpath:mapper/*.xml")) / / configure custom TypeHandler sqlSessionFactoryBean.setTypeHandlers (new TypeHandler [] {new VarcharTypeHandler ()});} catch (IOException e) {e.printStackTrace ();} return sqlSessionFactoryBean;}

Add typeHandler to the actions and fields that need to be used

Insert into user (id, create_date, `name`, did, `password`, username) values (# {id,jdbcType=BIGINT}, # {createDate,jdbcType=TIMESTAMP}, # {name,jdbcType=VARCHAR}, # {did,jdbcType=BIGINT}, # {password,jdbcType=VARCHAR}, # {username,jdbcType=VARCHAR,typeHandler=varcharTypeHandler}) 3, test package javaDIYFree.dao;import javaDIYFree.config.MybatisConfig;import javaDIYFree.model.User;import org.junit.Test;import org.junit.runner.RunWith Import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.function.Consumer;/** * @ author Hearts * @ date 2019-4-17 * @ desc * / @ RunWith (SpringJUnit4ClassRunner.class) @ ContextConfiguration (classes = MybatisConfig.class) public class UserMapperTest {@ Autowired private UserMapper userMapper @ Test / * Test insert method * / public void insertUser () {User user = new User (); user.setUsername ("zhangsan"); user.setPassword ("123456"); userMapper.insert (user) } @ Test / * Test selectAll method * / public void selectAllUser () {userMapper.selectAll () .forEach (new Consumer () {public void accept (User I) {/ / print username and password System.out.println (i.getUsername () + "= >" + i.getPassword ());}}) 4. Project structure diagram

Thank you for your reading, the above is the content of "what is the method of mybatis TypeHandler injecting spring dependency". After the study of this article, I believe you have a deeper understanding of what the method of mybatis TypeHandler injection spring dependency is, 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