当前版本:Spring5.3.0
、MyBatis3.2.2
、mybatis-spring1.2.0
1.声明
当前内容主要为本人复习和操作当前的Spring与MyBatis整合操作,深入理解其中的意思.
2.pom依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<!-- <spring.version>5.1.5.RELEASE</spring.version> -->
<!-- 用于5.3.0版本用于测试当前的r2dbc -->
<spring.version>5.3.0</spring.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<!-- <dependency> 这个是最近新建立的2020都在更新 <groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId> <version>2.1.1</version> </dependency> -->
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- 导入最基本的spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm,其中包含了jpa和hibernate -->
<!-- 配置Hibernate与Spring之间的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!-- 导入mybatis的依赖 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.2</version>
</dependency>
<!-- 导入MyBatis对Spring的依赖 -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.0</version>
</dependency>
</dependencies>
主要在Spring原来的包的基础上面添加:mybatis和mybatis-spring(主要整合Spring时使用的)
这两个包
3.编写applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd" >
<context:property-placeholder location="classpath:/com/hy/java/spring/database/mybatis/xml/db.properties"/>
<!-- SessionFactory, DataSource, etc. omitted -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 扫描包并将实体类进行别名映射,即User -->
<!-- <property name="typeAliasesPackage" value="com.hy.java.spring.database.mybatis.xml.entity"></property> -->
<property name="configLocation" value="classpath:/com/hy/java/spring/database/mybatis/xml/mybatis-config.xml"></property>
<!-- 用来扫描当前的dao层对应的映射文件 -->
<property name="mapperLocations">
<list>
<value>classpath:/com/hy/java/spring/database/mybatis/xml/mapper/UserMapper.xml</value>
</list>
</property>
</bean>
<!-- 这个就是为当前的dao层创建mybatis的代理类,方便执行配置文件中的sql -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.hy.java.spring.database.mybatis.xml.dao"></property>
</bean>
<bean id="userService" class="com.hy.java.spring.database.mybatis.xml.service.UserService">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:advice transaction-manager="txManager" id="txAdvice">
<tx:attributes>
<!-- 以update、insert、delete开头的需要事务 -->
<!-- <tx:method name=""/> -->
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.hy.java.spring.database.mybatis.xml.service.*.*(..))" id="txPointcut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
1. 其中SqlSessionFactoryBean
这个bean就是用来装载:mapper映射文件(mapperLocations)、mybatis的配置文件(configLocation)、类别名处理用的(typeAliasesPackage)
2.其中最重要的就是MapperScannerConfigurer
这个bean:这个主要就是用扫描当前的XML配置文件并为其创建基于Dao层的代理类的然后将这个代理类注入到Spring的IOC容器中,让你在调用Dao的时候返回代理,执行已经加载的sql,最后返回结果!
4.demo
当前的mybatis-config.xml文件主要用来打印sql执行过程
<?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>
<settings>
<!-- 打印sql执行过程,这个value可以是mybatis官方中内容 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
</configuration>
实体类User.java
public class User {
private int id;
private String name;
//省略各种get、set、toString方法
}
UserDao.java
public interface UserDao {
public User findById(Integer id);
}
UserDao对应的xml配置文件:
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hy.java.spring.database.mybatis.xml.dao.UserDao">
<!-- 如果使用了包别名映射,就可以直接使用User -->
<select id="findById" parameterType="int" resultType="com.hy.java.spring.database.mybatis.xml.entity.User">
select * from user where id =#{id}
</select>
</mapper>
其中mapper映射文件中的namespace+id是唯一的,且查找当前的执行方法就是:namespace+id方式组成对应需要执行方法的sql
UserService.java
// 注意service层才是存放事务的操作
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public User getUserById(Integer id) {
return userDao.findById(id);
}
}
测试类MyBatisXmlTest .java
public class MyBatisXmlTest {
public static void main(String[] args) {
String xml="/com/hy/java/spring/database/mybatis/xml/applicationContext.xml";
ApplicationContext context =new ClassPathXmlApplicationContext(xml);
UserService userDao = context.getBean(UserService.class);
System.out.println(userDao.getUserById(1));
}
}
执行结果:
SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Logging initialized using ‘class org.apache.ibatis.logging.stdout.StdOutImpl’ adapter.
Creating a new SqlSession
Registering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@172b013]
JDBC Connection [jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC, UserName=root@localhost, MySQL Connector Java] will be managed by Spring
ooo Using Connection [jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC, UserName=root@localhost, MySQL Connector Java]
==> Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<== Columns: id, name, pwd, age, adress, createTime
<== Row: 1, Joe, 000000, 18, 4564, 2020-04-01 09:14:56
Releasing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@172b013]
Transaction synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@172b013]
User [id=1, name=Joe]
执行成功!
5.总结
- Spring与MyBatis整合的时候需要两个对象:
SqlSessionFactoryBean和MapperScannerConfigurer
,一个打开和关闭session,一个为需要映射的dao接口创建代理执行对象
- 如果
缺少MapperScannerConfigurer那么就会出现找不到UserDao的问题