概述
mybatis为我们提供数据持久化技术,在持久层发挥一定的作用。
spring中的ioc
为我们提供解耦用来降低程序代码之间的耦合度。aop
为我们提供了一定的事物控制,也称动态代理,使我们开发更加便捷、效率更快,在业务层发挥一定的作用。
整合步骤
- 添加所需jar包
- 创建实体类
- 建立数据访问接口
- 配置sql映射文件
- 配置mybatis配置文件
- 配置DataSource数据源
- 配置SqlSessionFactoryBean
- 使用SqlSessionTemplate进行数据持久化操作
- 配置声明式事务
- 添加业务层
准备jar包
- mybatis必备包:
mybatis-3.4.5.jar
- spring容器将对象封装到ioc容器中:
spring-context.5.0.2.RELEASE
- 连接数据库需要的数据源:
spring-jdbc.5.0.2.RELEASE
- 事物控制:
spring-tx.5.0.2.RELEASE
- aop切入点表达式解析:
aspectjweaver.1.8.7
- 链接数据库:
mysql-connector-java.8.0.16
- 由于spring开发速度比mybatis开发速度快,因此spring开发团队不想再发布一个基于非发布版本的mybatis的整合支持,为了spring能够支持mybatis,因此后来,mybatis团队按照spring集成ORM框架的统一风格开发了相关整合组件,方便开发者在spring中集成使用mybatis。
综上所诉:mybatis-spring整合包:mybatis-spring.1.3.0
- 如果还想自己完成单元测试、日志输出可以导入:
log4j.1.2.12
、junit
注意事项
由于包涉及得多,建议创建maven工程,在pom.xml
文件下,书写如下配置,再导入即可(如果缺少jar包会自动下载,默认是C盘,可自己设置切换,具体操作百度)。
<?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>org.example</groupId>
<artifactId>spring_mybatis_xml</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- 数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- spring容器 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- aop切入点表达式解析 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!-- 事务控制 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- 测试 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
创建实体类
顾名思义,我们需要将数据库的字段映射到实体类当中。就是我们经常说的ORM(对象/关系映射)。使对象模型和关系数据库的表之间建立了一座桥梁。
我们在数据库中,创建如下样式:
基于上面的ORM模型,我们就应该在项目工程中,创建这样一个实体类,与之一一对应,需要注意的是,为了后面开发更加便捷,不容易出错,对于数据类型,变量名,必须一模一样。结束之后,创建getter
、setter
方法。为了看到结果,可以再重写tostring
方法
package domain;
public class Account {
int id;
String name;
double money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
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 double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
建立数据访问接口
在该接口中,通常我们包含,简单的增删改查。更加复杂的操作,我们留在业务层当中,通过不同的增删改查嵌套可以做到。
package dao;
import domain.Account;
import java.util.List;
public interface IAccountDao {
// 1. 根据姓名查看用户
Account findAccountByName(String name);
// 2. 根据用户信息更新用户
void updateAccount(Account account);
// 3. 查询所有用户
List<Account> findAllAccount();
}
配置SQL映射文件
mybatis的好处就在于,将具体的SQL操作,放在如下xml配置文件当中,我们只需要关注sql语句即可。其他的工作,mybatis会为我们映射过去。
注意事项
我们的实体类的包路径是,怎么样它就应该创建怎么样,并且文件名也要一模一样,只修改后缀名即可。
<?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">
<!-- 1. 配置Dao层。mybatis的好处好像,解决了Dao层的实体类。
开始提问,解决了实体类。我事务怎么加?
-->
<mapper namespace="dao.IAccountDao">
<!--1. 根据姓名查看用户 -->
<select id="findAccountByName" resultType="domain.Account">
select * from account where name = #{name}
</select>
<!--2. 根据用户信息更新用户 -->
<update id="updateAccount">
update account
<set>
<if test="name != null and name != ''">
name = #{name} ,
</if>
<if test="money >= 0">
money = #{money} ,
</if>
</set>
where id = #{id}
</update>
<!--3. 查询所有用户 -->
<select id="findAllAccount" resultType="domain.Account">
select * from account
</select>
</mapper>
配置mybatis配置文件
该步骤,对于我目前的开发水平,仍未达到,如果需要改步骤的,可以自行添加,需要注意的是,该配置文件就是mybatis的核心配置文件configuration.xml
,当时我们在该配置文件当中,设置了数据源、映射关系,但在整合过程中,我们就不需要再在mybatis中设置了,我们都交给spring去完成。因此,如果没其他的要求,这个步骤是可以省略的。
配置DataSource数据源
这里使用spring提供的数据源DriverManagerDataSource
即可。具体配置如下:
<!-- 配置数据源 -->
<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/bilibili_ioc?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
配置SqlSessoionFactoryBean
还记得,我们在mybatis中,是如何获取的然后进行增删改查的吗?
在MyBatis中,SqlSessionFactory的实例需要使用SqISessionFactoryBuilder创建;而在集成环境中,则可以使用MyBatis-Spring整合包中的 SqISessionFactoryBean来代替。SqISessionFactoryBean封装了使用SqISessionFactoryBuilder创建SqISessionFactory的过程,我们可以在Spring中以配置文件的形式,通过配置SqlSessionFactoryBean获得SqlSessionFactory实例。关键配置如下所示:
<!-- 配置sqlsessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源给他 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置数据库表对应的java实体类 -->
<property name="typeAliasesPackage" value="domain.*" />
<!-- 配置SQL映射文件信息 -->
<property name="mapperLocations" value="classpath:dao/IAccountDao.xml" />
</bean>
SqlSessionTemplate进行数据持久化操作
实现数据访问接口,创建sqlsessiontemplate
对象真正意义上的完成,映射全部工作。由于在该类使用到了SqlSessionTemplate
别忘了将对象添加到ioc容器中哟。
package dao.impl;
import dao.IAccountDao;
import domain.Account;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class AccountDaoImpl implements IAccountDao {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public Account findAccountByName(String name) {
// 给转账添加事务
List<Account> list = sqlSessionTemplate.selectList("dao.IAccountDao.findAccountByName",name);
System.out.println(list);
if(list.size() > 1 || list == null)
throw new RuntimeException("结果集不唯一、未找到这个人");
return list.get(0);
}
public void updateAccount(Account account) {
sqlSessionTemplate.update("dao.IAccountDao.updateAccount",account);
}
public List<Account> findAllAccount() {
return sqlSessionTemplate.selectList("dao.IAccountDao.findAllAccount");
}
}
添加声明式事务控制
以上的操作,有一个弊端,对于这些都默认添加了自动提交,因此,当我们数据发生错误的时候,比如转账,转到一半突然网断了,导致另外一个人没有接受的到,这就导致了转账失败,事务出现了问题。因此我们需要,添加声明式事务控制。
具体操作详解,可以看 spring基于xml的声明式事务控制
<!-- 1. 添加事务管理 -->
<bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 2. 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="txManger">
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 3. 配置AOP中通用切入点 -->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* service.impl.*.*(..))"/>
<!-- 4. 建立切入点表达式和切入点表达式的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
添加业务层
业务层更多的就是对持久层的一个调用,然后完成一些复杂的增删改查的操作。
这里直接为了方便理解,我只贴转账代码。细心的都看出来了,下面有一句错误,这就是为了模拟当程序出现错误的时候,测试能否完成事务控制。
public void transfer(String giveName, String receiveName,double money) {
// 1. 查找人
Account user1 = accountDao.findAccountByName(giveName);
Account user2 = accountDao.findAccountByName(receiveName);
// 2. 转账
user1.setMoney(user1.getMoney() - money);
user2.setMoney(user2.getMoney() + money);
// 3. 更新
accountDao.updateAccount(user1);
int a = 1/0;
accountDao.updateAccount(user2);
}
总结
以上便是一次完整的spring-mybatis整合过程。
在这里我贴一下所有的代码。以帮助理解。
项目结构
实体类
domain.Account
package domain;
public class Account {
int id;
String name;
double money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
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 double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
持久层
Dao.IAccountDao
package dao;
import domain.Account;
import java.util.List;
public interface IAccountDao {
// 1. 根据姓名查看用户
Account findAccountByName(String name);
// 2. 根据用户信息更新用户
void updateAccount(Account account);
// 3. 查询所有用户
List<Account> findAllAccount();
}
Dao.Impl.AccountDaoImpl
package dao.impl;
import dao.IAccountDao;
import domain.Account;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class AccountDaoImpl implements IAccountDao {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public Account findAccountByName(String name) {
// 给转账添加事务
List<Account> list = sqlSessionTemplate.selectList("dao.IAccountDao.findAccountByName",name);
System.out.println(list);
if(list.size() > 1 || list == null)
throw new RuntimeException("结果集不唯一、未找到这个人");
return list.get(0);
}
public void updateAccount(Account account) {
sqlSessionTemplate.update("dao.IAccountDao.updateAccount",account);
}
public List<Account> findAllAccount() {
return sqlSessionTemplate.selectList("dao.IAccountDao.findAllAccount");
}
}
业务层
service.IAccountService
package service;
import domain.Account;
import java.util.List;
public interface IAccountService {
// 1. 查询所有用户
List<Account> findAllAccount();
// 2. 转账
void transfer(String giveName,String receiveName,double money);
}
service.Impl.AccountServiceImpl
package service.impl;
import dao.IAccountDao;
import domain.Account;
import service.IAccountService;
import java.util.List;
public class AccountServiceImpl implements IAccountService {
IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
public void transfer(String giveName, String receiveName,double money) {
// 1. 查找人
Account user1 = accountDao.findAccountByName(giveName);
Account user2 = accountDao.findAccountByName(receiveName);
// 2. 转账
user1.setMoney(user1.getMoney() - money);
user2.setMoney(user2.getMoney() + money);
// 3. 更新
accountDao.updateAccount(user1);
int a = 1/0;
accountDao.updateAccount(user2);
}
}
配置文件
dao.IAccountDao.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">
<!-- 1. 配置Dao层。mybatis的好处好像,解决了Dao层的实体类。
开始提问,解决了实体类。我事务怎么加?
-->
<mapper namespace="dao.IAccountDao">
<!--1. 根据姓名查看用户 -->
<select id="findAccountByName" resultType="domain.Account">
select * from account where name = #{name}
</select>
<!--2. 根据用户信息更新用户 -->
<update id="updateAccount">
update account
<set>
<if test="name != null and name != ''">
name = #{name} ,
</if>
<if test="money >= 0">
money = #{money} ,
</if>
</set>
where id = #{id}
</update>
<!--3. 查询所有用户 -->
<select id="findAllAccount" resultType="domain.Account">
select * from account
</select>
</mapper>
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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 把dao层添加到spring容器中 -->
<bean id="accountDao" class="dao.impl.AccountDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- 把service层添加到spring容器中 -->
<bean id="accountService" class="service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!-- 1. 添加事务管理 -->
<bean id="txManger" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 2. 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="txManger">
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 3. 配置AOP中通用切入点 -->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* service.impl.*.*(..))"/>
<!-- 4. 建立切入点表达式和切入点表达式的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
<!-- 配置sqlsessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源给他 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置数据库表对应的java实体类 -->
<property name="typeAliasesPackage" value="domain.*" />
<!-- 配置SQL映射文件信息 -->
<property name="mapperLocations" value="classpath:dao/IAccountDao.xml" />
</bean>
<!-- 配置数据源 -->
<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/bilibili_ioc?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
</beans>