Spring5入门-12-整合Mybatis
一、前言
- 参考视频:遇见狂神说-Spring5
- 参考文档:mybatis-spring
环境:
- mysql8.0.21
- Spring 5.2.9
- mybaits 3.5.5
- mybatis-spring 2.0.5
- junit 4.12
要注意的事情:
在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。这很重要——因为本手册中不会提供二者的基本内容,安装和配置教程。
MyBatis-Spring 需要以下版本:
MyBatis-Spring MyBatis Spring 框架 Spring Batch Java 2.0 3.5+ 5.0+ 4.0+ Java 8+ 1.3 3.4+ 3.2.2+ 2.1+ Java 6+
二、环境-回顾mybatis
2.1 依赖
<!--mysql8-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--Spring-JDBC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--Mybaits-Spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!--AOP织入-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!--JUnit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
2.2 数据库
2.3 pojo
package com.duzhuan.pojo;
/**
* @Autord: HuangDekai
* @Date: 2020/10/11 15:35
* @Version: 1.0
* @since: jdk11
*/
public class User {
private int id;
private String name;
private String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
2.4 mybatis配置文件
路径
代码
mybaits-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>
<properties resource="db.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.duzhuan.pojo"/>
</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 class="com.duzhuan.mapper.UserMapper"/>
</mappers>
</configuration>
这里已经预先配好了mapper,请选择合适自己路径的mapper。
db.properties
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC
username = root
password = qq123456
2.5 mapper
路径
注意事项
在此处的xml
文件等配置文件,由于是Maven项目的原因,很有可能不能复制到target目录下,即真正运行的路径下没有UserMapper.xml
,因此需要在pom.xml的根标签中加入以下配置:
<build>
<resources>
<resource>
<directory>src/main/resource/</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java/</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
代码
UserMapper:
package com.duzhuan.mapper;
import com.duzhuan.pojo.User;
import java.util.List;
/**
* @Autord: HuangDekai
* @Date: 2020/10/11 20:06
* @Version: 1.0
* @since: jdk11
*/
public interface UserMapper {
List<User> getUserList();
}
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.duzhuan.mapper.UserMapper">
<select id="getUserList" resultType="User">
select * from mybatis.user
</select>
</mapper>
2.6 测试类
路径
代码
UserMapperTest:
package com.duzhuan.mapper;
import com.duzhuan.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;
/**
* @Autord: HuangDekai
* @Date: 2020/10/11 20:16
* @Version: 1.0
* @since: jdk11
*/
public class UserMapperTest {
@Test
public void userMapperTest() throws IOException {
String config = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(config);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
}
结果
三、Mybatis-Spring SqlSessionTemplate
基于以上环境,对其进行修改。
-
创建spring-dao.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="db.properties"/> <!--使用spring的数据源替换Mybatis的配置 这里使用spring提供的JDBC--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="qq123456"/> </bean> </beans>
这样就可以删掉mybatis-config.xml相关的部分:
<properties resource="db.properties"/> <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>
-
设置mybatis配置和导入mybatis配置。其实可以完全由Spring配置,但我习惯将
<settings>
和typeAliases
放在mybatis的配置文件中,因此会用到导入mybatis配置:<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="db.properties"/> <!--使用spring的数据源替换Mybatis的配置 这里使用spring提供的JDBC--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="qq123456"/> </bean> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 导入mybatis的配置 其实可以纯spring配置mybatis,无需导入。 --> <property name="configLocation" value="mybatis-config.xml"/> <!--比如这个,绑定UserMapper--> <property name="mapperLocations" value="classpath:com/duzhuan/mapper/UserMapper.xml"/> </bean> </beans>
由于有
<property name="mapperLocations" value="classpath:com/duzhuan/mapper/UserMapper.xml"/>
,因此可以删掉mybatis-config.xml
中的:<mappers> <mapper class="com.duzhuan.mapper.UserMapper"/> </mappers>
-
配置
sqlSession
:-
spring-mybatis中,是没有
sqlSession
的,sqlSessionTemplate
等价于sqlSession
。打开org.mybatis.spring.SqlSessionTemplate
可以看到的是:它没有Setter方法,只能构造器注入。
-
在spring-dao.xml中添加:
<!--sqlSession--> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
-
-
有了
sqlSession
,下一步就应该getMapper
了。创建UserMapperImpl:
代码:
package com.duzhuan.mapper; import com.duzhuan.pojo.User; import org.mybatis.spring.SqlSessionTemplate; import java.util.List; /** * @Autord: HuangDekai * @Date: 2020/10/12 15:29 * @Version: 1.0 * @since: jdk11 */ public class UserMapperImpl implements UserMapper{ private SqlSessionTemplate sqlSessionTemplate; public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } @Override public List<User> getUserList() { UserMapper userMapper = sqlSessionTemplate.getMapper(UserMapper.class); return userMapper.getUserList(); } }
在spring-dao.xml中添加:
<!--Mapper--> <bean id="userMapper" class="com.duzhuan.mapper.UserMapperImpl"> <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/> </bean>
-
修改UserMapperTest:
package com.duzhuan.mapper; import com.duzhuan.pojo.User; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.io.IOException; import java.util.List; /** * @Autord: HuangDekai * @Date: 2020/10/11 20:16 * @Version: 1.0 * @since: jdk11 */ public class UserMapperTest { @Test public void userMapperTest() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); List<User> userList = userMapper.getUserList(); for (User user : userList) { System.out.println(user); } } }
运行测试样例结果:
附上spring-dao.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="db.properties"/> <!--使用spring的数据源替换Mybatis的配置 这里使用spring提供的JDBC--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC"/> <property name="username" value="root"/> <property name="password" value="qq123456"/> </bean> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 导入mybatis的配置 其实可以纯spring配置mybatis,无需导入。 --> <property name="configLocation" value="mybatis-config.xml"/> <!--比如这个,绑定UserMapper--> <property name="mapperLocations" value="classpath:com/duzhuan/mapper/UserMapper.xml"/> </bean> <!--sqlSession--> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> <!--Mapper--> <bean id="userMapper" class="com.duzhuan.mapper.UserMapperImpl"> <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/> </bean> </beans>
四、SqlSessionDaoSupport
另外一种方法。
创建一个UserMapper的实现类UserMapperDaoSupport:
代码:
package com.duzhuan.mapper;
import com.duzhuan.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
/**
* @Autord: HuangDekai
* @Date: 2020/10/12 17:25
* @Version: 1.0
* @since: jdk11
*/
public class UserMapperDaoSupportImpl extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> getUserList() {
return getSqlSession().getMapper(UserMapper.class).getUserList();
}
}
在spring-dao.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="db.properties"/>
<!--使用spring的数据源替换Mybatis的配置
这里使用spring提供的JDBC-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="qq123456"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--
导入mybatis的配置
其实可以纯spring配置mybatis,无需导入。
-->
<property name="configLocation" value="mybatis-config.xml"/>
<!--比如这个,绑定UserMapper-->
<property name="mapperLocations" value="classpath:com/duzhuan/mapper/UserMapper.xml"/>
</bean>
<!--sqlSession-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!--Mapper-->
<bean id="userMapper" class="com.duzhuan.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<!--====================add===============-->
<bean id="UserMapperDaoSupportImpl" class="com.duzhuan.mapper.UserMapperDaoSupportImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!--====================add===============-->
</beans>
运行结果: