Spring-Mybatis整合 | 原理分析
Posted wei_shuo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring-Mybatis整合 | 原理分析相关的知识,希望对你有一定的参考价值。
🌐Hello World !
文章目录
▌环境搭建
步骤:
导入相关jar包
- junit
- mybatis
- mysql
- spring
- aop织入
- mybatis-spring
环境搭建:
<dependencies> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!--spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.0.RELEASE</version> </dependency> <!--spring操作数据库,需要spring-jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!--aop织入--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> </dependencies>
▌Mybatis流程回顾
- 编写实体类
package com.wei.pojo; import lombok.Data; @Data public class User private int id; private String name; private String pwd;
- 编写核心配置文件
<?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核心配置文件--> <configuration> <!--引入外部配置文件--> <!--<properties resource="jdbc.properties"/>--> <settings> <!--标准日志工厂实现--> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <package name="com.wei.pojo.User"/> </typeAliases> <!--环境配置--> <environments default="development"> <environment id="development"> <!--事物管理--> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper class="com.wei.Mapper.UserMapper"/> </mappers> </configuration>
- 编写接口
package com.wei.Mapper; import com.wei.pojo.User; import java.util.List; public interface UserMapper public List<User> selectUser();
- 编写Mapper映射文件
<?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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.wei.Mapper.UserMapper"> <!--select查询语句查询全部用户--> <select id="selectUser" resultType="com.wei.pojo.User"> select * from mybatis.user; </select> </mapper>
- 测试
import com.wei.Mapper.UserMapper; import com.wei.pojo.User; 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 java.io.IOException; import java.io.InputStream; import java.util.List; public class MyTest @Test public void test() throws IOException String resources = "mybatis-config.xml"; //读取mybatis-config.xml主配置文件 InputStream in = Resources.getResourceAsStream(resources); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession sqlSession = sessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.selectUser(); for (User user : userList) System.out.println(user); sqlSession.close();
▌Mybatis-Spring整合
SqlSessionTemplate方式
- 要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:一个
SqlSessionFactory
和至少一个数据映射器类。- 在 MyBatis-Spring 中,可使用
SqlSessionFactoryBean
来创建SqlSessionFactory
。 要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中- 在基础的 MyBatis 用法中,是通过
SqlSessionFactoryBuilder
来创建SqlSessionFactory
的。而在 MyBatis-Spring 中,则使用SqlSessionFactoryBean
来创建
- 编写UserMapper接口类
package com.wei.Mapper; import com.wei.pojo.User; import java.util.List; public interface UserMapper public List<User> selectUser();
- 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"> <!--namespace=绑定一个对应的Dao/Mapper接口--> <mapper namespace="com.wei.Mapper.UserMapper"> <!--select查询语句查询全部用户--> <select id="selectUser" resultType="com.wei.pojo.User"> select * from mybatis.user; </select> </mapper>
- UserMapperImpl实现类,接口增加实现类
package com.wei.Mapper; import com.wei.pojo.User; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; public class UserMapperImpl implements UserMapper //以前来有操作使用SqlSession执行,现在所有操作在SqlSessionTemplate private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) this.sqlSession = sqlSession; public List<User> selectUser() UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser();
- User接口
package com.wei.pojo; import lombok.Data; @Data public class User private int id; private String name; private String pwd;
- 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核心配置文件--> <configuration> <!--引入外部配置文件--> <!--<properties resource="jdbc.properties"/>--> <settings> <!--标准日志工厂实现--> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <package name="com.wei.pojo"/> </typeAliases> <!--环境配置--> <environments default="development"> <environment id="development"> <!--事物管理--> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- <mappers>--> <!-- <mapper class="com.wei.Mapper.UserMapper"/>--> <!-- </mappers>--> </configuration>
- log4j.properties资源包
log4j.properties #将等级为DEBUG的日志信息输出到console和file两个目的地 log4j.rootLogger=DEBUG,console,file #控制台输出的相关设置 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 #文件输出的相关配置 log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/wei.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】[%dyy-MM-dd【%c】%m%n #日志输出级别 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.sql.PreparedStatement=DEBUG
- spring-dao.xml(将sqlSessionFactory等bean注入到spring框架中,来管理持久层中的操作)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--DataSource:使用Spring的数据源替换Mybatis的配置--> <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"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--配置数据源--> <property name="dataSource" ref="dataSource"/> <!-- 当你需要使用mybatis-config.xml 配置文件的时候你就需要配置config-location, config-location的作用是确定mybatis-config.xml文件位置的, 而mapper-locations是用来注册你写的xxxmapper.xml文件。如果你使用了mybatis-config.xml, 并且里面配置了mapper,那就不需要mapper-locations mapper-locations是一个定义mapper接口位置的属性,在xxx.yml或xxx.properties下配置,作用是实现mapper接口配置 --> <!--绑定Mybatis配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/wei/Mapper/*.xml"/> </bean> <!--SqlSessionTemplate:就是我们使用的sqlSessiion--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--只能使用构造器注入,应为没有set方法--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!--注入UserMapperImpl实现类--> <bean id="userMpaaer" class="com.wei.Mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> </beans>
- ApplicationContext.xml(配置Spring框架所需的信息)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--import,一般用于团队开发中,可以将多个配置文件导入合并为一个--> <import resource="spring-dao.xml"/> <!--注入UserMapperImpl实现类--> <bean id="userMpaaer" class="com.wei.Mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> </beans>
- 测试
import com.wei.Mapper.UserMapper; import com.wei.pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; public class MyTest @Test public void test() throws IOException //解析beans.xml文件,生成管理相应的Bean对象 ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml"); // UserMapper userMpaaer = context.getBean("userMpaaer", UserMapper.class); UserMapper userMpaaer = (UserMapper) context.getBean("userMpaaer"
Spring-Mybatis --- 配置SqlSessionFactoryBean,整合Spring-Mybatis(转)
要利用Mybatis首先是需要导入mybatis-x.x.x.jar,其次,要整合Spring和Mybatis需要导入mybatis-spring-x.x.x.jar。
JAR : mybatis-x.x.x
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.6</version> </dependency>JAR : mybatis-spring-x.x.x
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency>1、Spring整合Mybatis的xml配置
xml : POM
<!-- DB --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-servlet-api</artifactId> <version>7.0.54</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>7.0.23</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.18</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.6</version> </dependency>xml : DataSource
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close"> <property name="poolProperties"> <bean class="org.apache.tomcat.jdbc.pool.PoolProperties"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.user}" /> <property name="password" value="${jdbc.password}" /> <!-- Register the pool with JMX. In order for the connection pool object to create the MBean. --> <property name="jmxEnabled" value="true" /> <!-- The indication of whether objects will be validated by the idle object evictor. --> <property name="testWhileIdle" value="true" /> <!-- The indication of whether objects will be validated before being borrowed from the pool. --> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="initialSize" value="${jdbc.initialPoolSize}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxIdle" value="${jdbc.maxIdle}" /> <property name="maxAge" value="60000" /> <!-- The number of milliseconds to sleep between runs of the idle connection validation/cleaner thread. --> <property name="timeBetweenEvictionRunsMillis" value="15000" /> <!-- The minimum amount of time an object may sit idle in the pool before it is eligible for eviction. --> <property name="minEvictableIdleTimeMillis" value="60000" /> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="30" /> <property name="validationQuery" value="SELECT 1" /> <property name="validationInterval" value="30000" /> </bean> </property> </bean>
常用配置:
(如果在mybatis-config.xml利用<mappers>进行xml映射文件的配置,就可以不用配置下面的mapperLocation属性了)
<!-- mybatis文件配置,扫描所有mapper文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:com/eliteams/quick4j/web/dao/*.xml"/> <!-- spring与mybatis整合配置,扫描所有dao,在单数据源的情况下可以不写sqlSessionFactoryBeanName --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.eliteams.quick4j.web.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory"/>-------------------------阿弥陀佛----佛祖保佑----永无BUG--------------------------
2、Spring和Mybatis整合的三种方式
一
SqlSessionFactoryBean来替代SqlSessionFactoryBuilder来创建SqlSession
利用mybatis映射文件**.xml来配置
SqlSessionFactoryBean有一个必须属性dataSource,另外其还有一个通用属性configLocation(用来指定mybatis的xml配置文件路径)。
Spring的xml配置:
<!-- 创建SqlSessionFactory,同时指定数据源--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 指定sqlMapConfig总配置文件,订制的environment在spring容器中不在生效--> <property name="configLocation" value="classpath:sqlMapConfig.xml"/> </bean>mybatis总配置文件sqlMapConfig.xml:
<configuration> <typeAliases> <typeAlias type="com.xxt.ibatis.dbcp.domain.User" alias="User" /> </typeAliases> <mappers> <mapper resource="com/xxt/ibatis/dbcp/domain/userMapper.xml" /> </mappers> </configuration>userMapper.xml:
<mapper namespace="com.xxt.ibatis.dbcp.dao.UserDao"> <resultMap type="User" id="userMap"> <id property="id" column="id" /> <result property="name" column="name" /> <result property="password" column="password" /> <result property="createTime" column="createtime" /> </resultMap> <select id="getUserById" parameterType="int" resultMap="userMap"> select * from user where id = #{id} </select> <mapper/>DAO层接口类UserDao.java:注意此处定义的接口方法需要和UserMapper.xml映射的<select>标签的id对应
public interface UserDao { public User getUserById(int id); }需要操作数据时调用的类UserService.java:
public class UserService { //此处省略sqlSession的获取方法 private SqlSession sqlSession; private UserDao userDao; public User getUserById(int id) { return userDao.getUserById(id); } }二
SqlSessionFactoryBean来替代SqlSessionFactoryBuilder来创建SqlSession
采用数据映射器(MapperFactoryBean)的方式
不用写mybatis映射文件
采用注解方式提供相应的sql语句和输入参数。
Spring的xml配置:
<!-- 引入jdbc配置文件 --> <context:property-placeholder location="jdbc.properties"/> <!--创建jdbc数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <property name="initialSize" value="${initialSize}"/> <property name="maxActive" value="${maxActive}"/> <property name="maxIdle" value="${maxIdle}"/> <property name="minIdle" value="${minIdle}"/> </bean> <!-- 创建SqlSessionFactory,同时指定数据源--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!--创建数据映射器,数据映射器必须为接口--> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.xxt.ibatis.dbcp.dao.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <bean id="userDaoImpl" class="com.xxt.ibatis.dbcp.dao.impl.UserDaoImpl"> <property name="userMapper" ref="userMapper"/> </bean>数据映射器UserMapper.java:
public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{userId}") User getUser(@Param("userId") long id); }DAO接口类UserDao.java:
public interface UserDao { public User getUserById(User user); }DAO接口实现类UserDaoImpl.java:
public class UserDaoImpl implements UserDao { private UserMapper userMapper; public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public User getUserById(User user) { return userMapper.getUser(user.getId()); } }三
SqlSessionFactoryBean来替代SqlSessionFactoryBuilder创建SqlSession
不采用采用数据映射器(MapperFactoryBean)的方式,改为MapperScannerConfigurer 进行扫描
不用写mybatis映射文件
采用注解方式提供相应的sql语句和输入参数。
采用注解方式省去定义mapper的Bean
MapperFactoryBean 创建的代理类实现了 UserMapper 接口,并且注入到应用程序中。 因为代理创建在运行时环境中(Runtime,译者注) ,那么指定的映射器必须是一个接口,而 不是一个具体的实现类。
上面的MapperFactoryBean配置有一个很大的缺点,就是系统有很多的配置文件时 全部需要手动编写,所以上述的方式已经不用了。
没有必要在 Spring 的 XML 配置文件中注册所有的映射器。相反,你可以使用一个 MapperScannerConfigurer , 它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。
Spring的xml配置:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.mybatis.spring.sample.mapper" /> </bean>basePackage 属性是让你为映射器接口文件设置基本的包路径。 你可以使用分号或逗号 作为分隔符设置多于一个的包路径。每个映射器将会在指定的包路径中递归地被搜索到。
注 意 , 没有必要去指定SqlSessionFactory 或 SqlSessionTemplate , 因为 MapperScannerConfigurer 将会创建MapperFactoryBean,之后自动装配。但是,如果你使 用了一个 以上的 DataSource,那 么自动装配可能会失效 。这种情况下 ,你可以使用 sqlSessionFactoryBeanName 或 sqlSessionTemplateBeanName 属性来设置正确的 bean 名称来使用。
以上是关于Spring-Mybatis整合 | 原理分析的主要内容,如果未能解决你的问题,请参考以下文章
Spring-Mybatis --- 配置SqlSessionFactoryBean,整合Spring-Mybatis(转)