一、整合前的准备
1. pom.xml
需要使用到的maven依赖:
<!--单元测试依赖-->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<!--spring依赖-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!--使用AOP织入,需要导入一个依赖包-->
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<!--Mysql驱动依赖-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--Mybatis依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--spring操作数据库的依赖-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>
<!--spring整合mybatis的依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
其中mybatis-spring是之前没有使用过的maven依赖
<!--spring整合mybatis的依赖-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
解决java目录下的资源导入不到target中的问题:
<!--在java目录下的资源时导不出的,所以我们需要手动配xml文件-->
<build>
<resources>
<resource>
<directory>src/main/resources</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>
资源文件编码的问题:
报错:com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1字节的 UTF-8 序列的字节 1 无效
<!--资源文件编码的问题-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
2. 相关类、接口和xxxMapper.xml的搭建
src\main\java\com\sdpei\pojo\User.java:
public class User implements Serializable {
private int id;
private String name;
private String passwd;
public User(int id) {
}
public User(int id, String name, String passwd) {
this.id = id;
this.name = name;
this.passwd = passwd;
}
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 getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", passwd='" + passwd + '\'' +
'}';
}
}
src\main\java\com\sdpei\mapper\UserMapper.java:
public interface UserMapper {
List<User> selUsers();
List<User> selUserById(int id);
List<User> selUserByOther(Map map);
int insertUser(Map map);
int delUserById(int id);
int updateUserById(int id);
}
src\main\java\com\sdpei\mapper\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接口-->
<mapper namespace="com.sdpei.mapper.UserMapper">
<!--查询-->
<select id="selUsers" resultType="com.sdpei.pojo.User" >
select * from `user`
</select>
<!--条件查询-->
<select id="selUserById" parameterType="int" resultType="com.sdpei.pojo.User">
select * from `user` where id = #{int}
</select>
<!--条件查询(map)-->
<select id="selUserByOther" parameterType="map" resultType="com.sdpei.pojo.User">
select * from `user` where id = #{userID} and `name`=#{userName}
</select>
<!--添加(map)-->
<insert id="insertUser2" parameterType="map">
insert into `user`(`id`, `name`, `passwd`) values (#{userId}, #{userName}, #{userPasswd})
</insert>
<!--删除-->
<delete id="delUser" parameterType="int">
delete from `user` where id=#{id}
</delete>
<!--修改-->
<update id="UpdataUser" parameterType="com.sdpei.pojo.User">
update `user` set `name` =#{name}, passwd=#{passwd} where id=#{id}
</update>
</mapper>
二、开始整合
第一步:编写mybatis-config.xml文件
其作用就是为了证明我们使用到了mybatis,其实spring是完全可以取代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>
<!--设置(他也可以被整合到spring中,不整合的目的只为了说明我们是使用了mybatis的)-->
<!-- <settings>-->
<!-- <setting name="" value=""/>-->
<!-- </settings>-->
<!--设置别名(他也可以被整合到spring中,不整合的目的只为了说明我们是使用了mybatis的)-->
<typeAliases>
<package name="com.sdpei.pojo"/>
</typeAliases>
</configuration>
第二步:需要准备一个spring-dao.xml文件(创建在resources下)
1.使用Spring的DriverManagerDataSource类取代mybatis中的dataSource进行数据库连接
2.在spring中配置sqlSessionFactoryBean
这个bean是用于给XxxMapperImpl的sqlSessionFactory属性注入使用的
3.绑定mybatis的核心配置文件>
其作用相当于将mybatis-config.xml中的配置引入该xml
4.实现mybatis中的mapper的注册
5.使用Spring中的SqlSessionTemplate完全取代mybatis中的SqlSession
这个bean是用于给SqlSessionDaoSupport类(官方)中的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: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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--DataSource:使用Spring的DataSource取代mybatis中的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?useUnicode=true&
characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root123123"/>
</bean>
<!--配置Spring提供的SqlSessionFactory-->
<!--是用于给XxxMapperImpl的sqlSessionFactory属性注入使用的-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis的核心配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--实现mybatis中的mapper的注册-->
<property name="mapperLocations" value="classpath:com/sdpei/mapper/*.xml"/>
</bean>
<!--使用SqlSessionTemplate取代原本mybatis中的SqlSession-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--因为没有set方法,所以注入的时候只能使用构造器注入-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
第三步:创建编写applicationContext.xml
applicationContext.xml的作用有两方面。
一方面,其作为原本spring的核心配置值文件,完成例如bean的注册、AOP的实现等配置;
另一方面,其作为一个spring配置文件的整合,上面有一个spring-dao.xml当我们学习了SpringMVC后还会有一个springMVC.xml.上述的两个文件都可以通过< import resource=“spring-dao.xml”/>和< import resource=“springMVC.xml”/>引入到applicationContext.xml。
这样我们只需要new ClassPathXmlApplicationContext(“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: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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--导入spring-dao.xml-->
<import resource="spring-dao.xml"/>
</beans>
第四步:创建UserMapper的实现类
在spring整合mybatis的过程中,创建UserMapper的实现类的和mybatis中差异比较大大的一个环节。
在mybatis阶段,我们写好UserMapper接口和UserMapper.xml在之后,就直接可以通过sqlSession获取mapper(getMapper(UserMapper.class)),然后直接执行UserMapper中的方法就可以。
但是在spring-mybatis中必须要通过实现了UserMapper接口的类(UserMapperImp)来调用注册在UserMapper.xml中的 I D U S 方法。
然后通过SqlSessionTemplate 对象或者SqlSession对象调用getMapper(xxxMapper.class)方法。
这一点应该也是大家就得比较繁琐的一点,其实这一些有点AOP的影子。
获取可用来调用getMapper(xxxMapper.class)方法的对象(SqlSessionTemplate /SqlSession)的方式有两种。
第一种方式:通过SqlSessionTemplate调用getMapper().
public class UserMapperImp implements UserMapper{
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> selUsers() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selUsers();
}
public List<User> selUserById(int id) {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selUserById(id);
}
public List<User> selUserByOther(Map map) {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selUserByOther(map);
}
public int insertUser(Map map) {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.insertUser(map);
}
public int delUserById(int id) {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.delUserById(id);
}
public int updateUserById(int id) {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.updateUserById(id);
}
}
因为在spring中是使用SqlSessionTemplate取代SqlSession,所以使用SqlSessionTemplate直接完成“增删改查”代码的。
既然需要使用到SqlSessionTemplate,那么类中就要有SqlSessionTemplate
在spring中,要对类中的属性进行注入,那么离不开set方法。
在完成UserMapperImp类的编写,需要去applicationContext.xml中完成bean的注册并完成属性的注入
测试:
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("UserMapperImp", UserMapper.class);
List<User> users = userMapper.selUsers();
for (User user : users) {
System.out.println(user);
}
System.out.println("test01()完成......");
}
第二种方式:通过Spring提供的getSqlSession()获取的sqlSession对象调用getMapper().
mybatis官方给提供了一个名为SqlSessionDaoSupport的类
SqlSessionDaoSupport类的作用就是创建SqlSessionTemplate
当继承了SqlSessionDaoSupport后,我们可以直接使用getSqlSession()获取sqlSession
分析一下源码:
继承SqlSessionDaoSupport并实现UserMapper接口:
public class UserMapperImp02 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selUsers() {
//获取sqlSession
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selUsers();
}
public List<User> selUserById(int id) {
//直接使用一条语句实现上一个方法中的三条语句
return getSqlSession().getMapper(UserMapper.class).selUserById(id);
}
public List<User> selUserByOther(Map map) {
return getSqlSession().getMapper(UserMapper.class).selUserByOther(map);
}
public int insertUser(Map map) {
return getSqlSession().getMapper(UserMapper.class).insertUser(map);
}
public int delUserById(int id) {
return getSqlSession().getMapper(UserMapper.class).delUserById(id);
}
public int updateUserById(int id) {
return getSqlSession().getMapper(UserMapper.class).updateUserById(id);
}
}
在applicationContext.xml中注册bean并对父类中的SqlSessionFactory进行注入:
测试:
@Test
public void test02(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("UserMapperImp02", UserMapper.class);
List<User> users = userMapper.selUsers();
for (User user : users) {
System.out.println(user);
}
System.out.println("test02()完成......");
}
完整的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: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/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--导入spring-dao.xml-->
<import resource="spring-dao.xml"/>
<!--注册bean-->
<bean id="UserMapperImp" class="com.sdpei.mapper.UserMapperImp">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<bean id="UserMapperImp02" class="com.sdpei.mapper.UserMapperImp02">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>