mybatis-spring integration

mybatis-spring integration

mybatis-spring integration

Prerequisites for integration: There is a mybatis project in advance, which is directly provided here to facilitate integration instructions.

  1. Project structure

  1. database

  1. Code

UserMapper.java

package dao; import pojo.User; import java.util.List; public interface UserMapper { List <the User> selectUser () ; } Copy code

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis -3-mapper.dtd" > <!--configuration core configuration file--> < mapper namespace = "dao.UserMapper" > < select id = "selectUser" resultType = "user" > select * from mybatis.user </select > </mapper > Copy code

User.java

package pojo; import lombok.Data; @Data public class User { private int id; private String name; private String pwd; } Copy code

log4j.properties

#Output the log information with the level of DEBUG to the two destinations of console and file. The definition of console and file are in the following code log4j.rootLogger = DEBUG,console,file #Related settings for console output log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold = DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout. ConversionPattern = [%c]-%m%n #File output related settings log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File = #File ./log/Log4j.log log4j.appender.file.MaxFileSize = 10mb log4j.appender.file.Threshold = DEBUG log4j.appender.file.layout = org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern = [%p][%d {yy-MM-dd}][%c]%m%n #Log output level log4j.logger.org.mybatis = DEBUG log4j.logger.java.sql = DEBUG log4j.logger.java.sql.Statement = DEBUG log4j .logger.java.sql.ResultSet = DEBUG log4j.logger.java.sq1.PreparedStatement = DEBUG Copy code

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis -3-config.dtd" > <!--configuration core configuration file--> < configuration > < properties resource = "db.properties"/> < settings > < setting name = "logImpl" value = "Log4j"/> < setting name = "mapUnderscoreToCamelCase" value = "true"/> </settings > < typeAliases > < typeAlias type = "pojo.User" alias = "user"/> </typeAliases > < environments default = "development" > < environment id = "development" > < transactionManager type = "JDBC"/> < dataSource type = "POOLED" > < property name = "driver" value = "${driver}"/> < property name = "url" value = "${url}"/> <property name = "username" value = "${username}"/> < property name = "password" value = "${password}"/> </dataSource > </environment > </environments > < mappers > < mapper resource = "dao/UserMapper.xml"/> </mappers > </configuration > Copy code

DemoTest.java

import dao.UserMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import pojo.User; import java.io.IOException; import java.io.InputStream; import java.util.List; public class DemoTest { @Test public void test () throws IOException { //Get configuration resource String resource = "mybatis-config.xml" ; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.selectUser(); for (User user: users) { System.out.println(user); } } } Copy code

pom.xml

<?xml version="1.0" encoding="UTF-8"?> < project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3 .org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < parent > < artifactId > Spring-Study </artifactId > < groupId > org.example </groupId > < version > 1.0-SNAPSHOT </version > </ parent> < modelVersion > 4.0.0 </modelVersion > < artifactId > spring-mybatis </artifactId > <!-- Import dependency--> < dependencies > <!--junit test--> < dependency > < groupId > junit </groupId > < artifactId > junit </artifactId > < version > 4.12 </version > </dependency > <!-- Lombok--> < dependency > < groupId > org.projectlombok </groupId > < artifactId >lombok </artifactId > < version > 1.18.10 </version > </dependency > <!-- log4j log--> < dependency > <groupId > log4j </groupId > < artifactId > log4j </ artifactId > < version > 1.2.17 </version > </dependency > <!--mybatis--> < dependency > < groupId >org.mybatis <!-- Static resource import--> < build > < resources > < resource > <directory > </ groupId> < artifactId > mybatis </artifactId > < version > 3.5.4 </version > </dependency > <!--mysql--> < dependency > < groupId > mysql </groupId > < artifactId > mysql-connector -java </artifactId > < version > 8.0.12 </version > </dependency > </dependencies> src/main/java </directory > < includes > < include > **/*.properties </include > < include > **/*.xml </include > </includes > < filtering > true </filtering > </resource >< resource > < directory > src/main/resources </directory > < includes > < include > **/*.properties </include > < include > **/*.xml </include > </includes > < filtering > true </filtering > </resource > </resources > </build > </project > copy code

In fact, mybatis-spring integration is to simplify the code. Instead of needing new, let the spring container create objects through spring bean configuration, and observe the code differences before and after integration.

method one

  1. Add dependencies required for integration
<!--spring-related--> < dependency > < groupId > org.springframework </groupId > < artifactId > spring-webmvc </artifactId > < version > 5.1.10.RELEASE </version > </dependency > < !--spring-jdbc connect to the database--> < dependency > < groupId > org.springframework </groupId > < artifactId > spring-jdbc </artifactId > < version > 5.3.4 </version > </dependency > <!--AOP weaving--> < dependency > <groupId > </dependency > <!-- mybatis-spring integration--> < dependency > < groupId > org.mybatis </groupId org.aspectj </groupId > < artifactId > aspectjweaver </artifactId > < version > 1.9.4 </version > > < artifactId > mybatis-spring </artifactId > < version > 2.0.2 </version > </dependency > Copy code
  1. Create spring configuration file (ApplicationContext.xml)
    1. Configure DataSource
    2. Configure sqlSessionFactory
    3. Configure sqlSessionTemplate
<!-- Configure the data source datasource--> < bean id = "datasource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource" > < property name = "driverClassName" value = "com.mysql.cj.jdbc. Driver"/> < property name = "url" value = "jdbc:mysql://localhost:3306/mybatis?useSSL=true & useUnicode=true & characterEncoding=UTF-8 & serverTimezone=UTC"/> <property name = "username" value = " root"/> < property name = "password" value = "123456"/> </bean > <!--sqlSessionFactory--> < bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean" > < property name = "dataSource" ref = "datasource"/> <!-- You can bind directly here Define mybatis configuration file--> < property name = "configLocation" value = "classpath:mybatis-config.xml"/> <!--Binding mybatis-config.xml--> < property name = "mapperLocations" value = "classpath:dao/*.xml"/> bean </ > <!--sqlSession --> <bean id = "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" > <!-- Only constructor injection can be used because it has no set method --> < constructor- Arg index = "0" REF = "SqlSessionFactory"/> </the bean > copy the code
  1. Write the interface implementation class, that is, the implementation class of UserMapper.java

UserMapperImpl.java

package dao; import org.mybatis.spring.SqlSessionTemplate; import pojo.User; import java.util.List; public class UserMapperImpl implements UserMapper { private SqlSessionTemplate sqlSession; public void setSqlSession (SqlSessionTemplate sqlSession) { this .sqlSession = sqlSession; } public List<User> selectUser () { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } } Copy code
  1. in
    ApplicationContext.xml
    Configure this implementation class
    UserMapperImpl.java
< The bean ID = "UserMapper" class = "dao.UserMapperImpl" > < Property name = "SQLSESSION" REF = "SQLSESSION"/> </the bean > copy the code
  1. Test class

DemoTest

import dao.UserMapper; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import pojo.User; import java.io.IOException; public class DemoTest { @Test public void test () throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext( "ApplicationContext.xml" ); UserMapper mapper = context.getBean( "userMapper" , UserMapper.class); for (User user: mapper.selectUser()) { System.out.println(user); } } } Copy code

Now let's take a look at the difference between after integration and before integration:

  1. Configure the data source to replace the environment configuration of mybatis-config.xml

  1. Configure sqlSessionFactory and sqlSession to replace the acquisition of sqlSession objects of the tool class.

  1. One more interface implementation class
    UserMapperImpl.java

  1. With more interface implementation classes, of course, there is also an additional bean for configuring the interface implementation classes. (in
    ApplicationContext.xml
    Configuration)

  1. The test class no longer needs to get the SqlSession:

  1. In contrast, the mybatis-config.xml configuration file has a lot less configuration, and the tool class is gone (directly in
    ApplicationContext.xml
    The SqlSession obtained by the tool class is implemented in)

Way two

The second method is a modification based on the first method.

  1. Modified the interface implementation class

UserMapperImpl2.java

package dao; import org.mybatis.spring.support.SqlSessionDaoSupport; import pojo.User; import java.util.List; public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { public List<User> selectUser () { return getSqlSession () getMapper (UserMapper.class) .selectUser ().; } } Copy code

  1. Modified the bean of the registered interface implementation class
< The bean ID = "userMapper2" class = "dao.UserMapperImpl2" > < Property name = "SqlSessionFactory" REF = "SqlSessionFactory"/> </the bean > copy the code
  1. If you use the second method to achieve, you can also omit the configuration
    sqlSession
<!--sqlSession--> < bean id = "sqlSession" class = "org.mybatis.spring.SqlSessionTemplate" > <!-- Only constructor injection can be used because it has no set method --> < constructor-arg index = "0" REF = "SqlSessionFactory"/> </the bean > copy the code

The second method is an improved version of the first method, which is more "lazy".