一、Spring整合MyBatis步骤
第一步 引入依赖包
// Equip.java
package com.bdqn.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
项目所依赖的jar包如下:
Maven: aopalliance:aopalliance:1.0
Maven: com.google.protobuf:protobuf-java:3.6.1
Maven: commons-dbcp:commons-dbcp:1.4
Maven: commons-pool:commons-pool:1.6
Maven: junit:junit:4.13
Maven: log4j:log4j:1.2.17
Maven: mysql:mysql-connector-java:8.0.18
Maven: org.aspectj:aspectjweaver:1.9.6
Maven: org.hamcrest:hamcrest:2.2
Maven: org.hamcrest:hamcrest-core:2.2
Maven: org.mybatis:mybatis:3.5.6
Maven: org.mybatis:mybatis-spring:2.0.6
Maven: org.springframework:spring-aop:5.3.4
Maven: org.springframework:spring-beans:5.3.4
Maven: org.springframework:spring-context:5.3.4
Maven: org.springframework:spring-core:5.3.4
Maven: org.springframework:spring-expression:5.3.4
Maven: org.springframework:spring-jcl:5.3.4
Maven: org.springframework:spring-jdbc:5.3.4
Maven: org.springframework:spring-tx:5.3.4
注意:使用Maven创建项目,需要用到的所有依赖包如上。其中Maven: org.mybatis:mybatis-spring:2.0.6是MyBatis使用Spring框架整合的依赖包。
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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bdqn</groupId>
<artifactId>s3-spring-mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>s3-spring-mybatis</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!-- Spring整合MyBatis所需要的包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
</dependencies>
<!-- 配置资源目录 -->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
第二步 编写实体类、三层模式
实体类 SysUser.java
package com.bdqn.pojo;
import java.util.Date;
/**
* 系统用户实体
*
* @author LILIBO
* @since 2021-05-14
*/
public class SysUser {
private Integer id; //id
private String account; //用户编码
private String realName; //用户名称
private String password; //用户密码
private Integer sex; //性别
private Date birthday; //出生日期
private String phone; //电话
private String address; //地址
private Integer roleId; //用户角色ID
private Integer createdUserId; //创建者
private Date createdTime; //创建时间
private Integer updatedUserId; //更新者
private Date updatedTime; //更新时间
private Integer age;//年龄
private String roleIdName; //用户角色名称
public Integer getAge() {
/*long time = System.currentTimeMillis()-birthday.getTime();
Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/
Date date = new Date();
Integer age = date.getYear() - birthday.getYear();
return age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Integer getCreatedUserId() {
return createdUserId;
}
public void setCreatedUserId(Integer createdUserId) {
this.createdUserId = createdUserId;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Integer getUpdatedUserId() {
return updatedUserId;
}
public void setUpdatedUserId(Integer updatedUserId) {
this.updatedUserId = updatedUserId;
}
public Date getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
public void setAge(Integer age) {
this.age = age;
}
public String getRoleIdName() {
return roleIdName;
}
public void setRoleIdName(String roleIdName) {
this.roleIdName = roleIdName;
}
@Override
public String toString() {
return "SysUser{" +
"id=" + id +
", account='" + account + '\'' +
", realName='" + realName + '\'' +
", password='" + password + '\'' +
", sex=" + sex +
", birthday=" + birthday +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
", roleId=" + roleId +
", createdUserId=" + createdUserId +
", createdTime=" + createdTime +
", updatedUserId=" + updatedUserId +
", updatedTime=" + updatedTime +
", age=" + age +
", roleIdName='" + roleIdName + '\'' +
'}';
}
}
数据库DAO接口 SysUserMapper.java
package com.bdqn.dao;
import com.bdqn.pojo.SysUser;
import java.util.List;
/**
* SysUserMapper数据访问层接口
*
* @author LILIBO
* @since 2021-05-14
*/
public interface SysUserMapper {
/**
* 查询用户列表
*
* @param sysUser
* @return
*/
public List<SysUser> selectSysUserList(SysUser sysUser);
}
MyBatis映射文件 SysUserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- SysUserMapper接口MyBatis映射文件 -->
<mapper namespace="com.bdqn.dao.SysUserMapper">
<!-- 当数据库中的字段信息与对象的属性不一致时需要通过resultMap来映射 -->
<resultMap id="SysUserResult" type="SysUser">
<result property="roleIdName" column="roleName"/>
</resultMap>
<!-- 查询用户列表-roleId为null时查询到0条数据 -->
<select id="selectSysUserList" parameterType="SysUser" resultMap="SysUserResult">
select u.*, r.roleName
from t_sys_user u,
t_sys_role r
where u.roleId = r.id
and u.roleId = #{roleId}
and u.realName like CONCAT('%', #{realName}, '%')
</select>
</mapper>
数据库接口实现类 SysUserMapperImpl.java
package com.bdqn.dao;
import com.bdqn.pojo.SysUser;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
/**
* SysUserMapper实现类(通过SqlSessionTemplate操作数据库)
*
* @author LILIBO
* @since 2021-05-14
*/
public class SysUserMapperImpl implements SysUserMapper {
// mybatis-spring包中提供的实现了SqlSession接口的类,用来操作数据库
private SqlSessionTemplate sqlSession;
/**
* 查询用户列表
*
* @param sysUser
* @return
*/
@Override
public List<SysUser> selectSysUserList(SysUser sysUser) {
return sqlSession.getMapper(SysUserMapper.class).selectSysUserList(sysUser);
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
}
服务层接口 SysUserService.java
package com.bdqn.service;
import com.bdqn.pojo.SysUser;
import java.util.List;
/**
* SysUserService服务层接口
*
* @author LILIBO
* @since 2021-05-14
*/
public interface SysUserService {
/**
* 获得用户列表
*
* @param sysUser
* @return
*/
public List<SysUser> getList(SysUser sysUser);
}
服务层接口实现类 SysUserServiceImpl.java
package com.bdqn.service;
import com.bdqn.dao.SysUserMapper;
import com.bdqn.pojo.SysUser;
import java.util.List;
/**
* SysUserService服务层实现类
*
* @author LILIBO
* @since 2021-05-14
*/
public class SysUserServiceImpl implements SysUserService {
private SysUserMapper sysUserMapper;
@Override
public List<SysUser> getList(SysUser sysUser) {
try {
return sysUserMapper.selectSysUserList(sysUser);
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
}
public void setSysUserMapper(SysUserMapper sysUserMapper) {
this.sysUserMapper = sysUserMapper;
}
}
第三步 配置MyBatis核心配置文件
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>
<!-- 类型别名,配置基础包,配置之后在Mapper.xml文件中可以使用类名称首字母小写方式简写 -->
<typeAliases>
<package name="com.bdqn.pojo" />
</typeAliases>
</configuration>
}
注意:将数据源的配置交给Spring完成,按如上配置,注释掉引入外部数据源配置和MyBatis数据源环境配置。
第四步 配置Spring核心配置文件
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: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">
<!-- 配置数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/cvs_db?serverTimezone=UTC&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="lilibo"/>
</bean>
<!-- 配置SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 引用数据库配置<bean id="dataSource"> -->
<property name="dataSource" ref="dataSource"/>
<!-- 引入MyBatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!--配置SQL映射文件信息-->
<property name="mapperLocations">
<list>
<value>classpath:com/bdqn/dao/**/*.xml</value>
</list>
</property>
</bean>
<!-- 配置SqlSessionTemplate -->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!--将sqlSessionFactory注入到sqlSessionTemplate中(ref="sqlSessionFactory" ==> <bean id="sqlSessionFactory">)-->
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- 配置Mapper -->
<bean id="sysUserMapper" class="com.bdqn.mapper.SysUserMapperImpl">
<property name="sqlSession" ref="sqlSessionTemplate" />
</bean>
<!-- 配置Service -->
<bean id="sysUserService" class="com.bdqn.service.SysUserServiceImpl">
<property name="sysUserMapper" ref="sysUserMapper" />
</bean>
</beans>
单元测试
在项目test下创建 SysUserTest.java
package com.bdqn;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
/**
* SysUser业务测试
*
* @author LILIBO
* @since 2021-05-14
*/
public class SysUserTest {
private Logger logger = Logger.getLogger(SysUserTest.class);
@Before
public void setUp() throws Exception {
}
@Test
public void testGetUserList() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
SysUserService userService = (SysUserService) ctx.getBean("sysUserService");
List<SysUser> userList = new ArrayList<SysUser>();
SysUser sysUser = new SysUser();
sysUser.setRealName("赵");
sysUser.setRoleId(2);
userList = userService.getList(sysUser);
for (SysUser userResult : userList) {
logger.debug("testGetUserList account: "
+ userResult.getAccount() + " and realName: "
+ userResult.getRealName() + " and roleId: "
+ userResult.getRoleId() + " and roleName: "
+ userResult.getRoleIdName() + " and address: "
+ userResult.getAddress());
}
}
}
至此,Spring整合MyBatis配置完成。
优化一 使用SqlSessionDaoSupport替换SqlSessionTemplate
除了直接使用SqlSessionTempIate获取SqlSession实例处理数据的方式外,MyBatis-Spring还提供了SqlSessionDaoSupport类来简化SqlSessionTemplate。通过 this.getSqlSession() 获取到 SqlSession 对象来执行数据库操作。
在 com.bdqn.dao 包下新建 SysUserMapperDaoSupportImpl.java
package com.bdqn.dao;
import com.bdqn.pojo.SysUser;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
/**
* 继承SqlSessionDaoSupport抽象类实现(通过getSqlSession()方法获得SqlSession对象操作数据库)
*
* @author LILIBO
* @since 2021-05-14
*/
public class SysUserMapperDaoSupportImpl extends SqlSessionDaoSupport implements SysUserMapper {
/**
* 查询用户列表
*
* @param sysUser
* @return
*/
@Override
public List<SysUser> selectSysUserList(SysUser sysUser) {
return this.getSqlSession().getMapper(SysUserMapper.class).selectSysUserList(sysUser);
}
}
注意:继承了SqlSessionDaoSupport之后,不需要定义属性SqlSession sqlSession直接通过this.getSqlSession()获取到 SqlSession 对象来执行数据库操作。
修改 applicationContext.xml 对应配置
<!-- 配置DAO 一、使用SqlSessionTemplate版本 -->
<!-- MyBatis-Spring提供了SqlSessionTemplate类,继承了SqlSession接口,操作数据库 -->
<!--<bean id="sysUserMapper" class="com.bdqn.dao.SysUserMapperImpl">
<property name="sqlSession" ref="sqlSessionTemplate" />
</bean>-->
<!-- 配置DAO 二、使用SqlSessionDaoSupport版本 -->
<!-- MyBatis-Spring提供了通过this.getSqlSession()方法获得SqlSession实例操作数据库,不需要定义SqlSession对象,使用起来更方便 -->
<bean id="sysUserMapper" class="com.bdqn.dao.SysUserMapperDaoSupportImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
注意:注释第一种方式SqlSessionTemplate版本,替换为第二种方式,使用SqlSessionDaoSupport版本。