文章目录
一、转账案类没有事务控制
1、持久层
持久层接口
public interface IAccountDao {
/**
* 根据id查询用户
* @param id
* @return
*/
Account findAccountById(Integer id);
Account findAccountByName(String accountName);
List<Account> findAll();
void updateAccount(Account source);
}
持久层重复代码类
/**
* 此类用于抽取Dao中的重复代码
*/
public class JdbcDaoSupport_example {
//定义JdbcTemplate让其他类继承该类 调用此方法
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setDataSource(DataSource dataSource) {
if(jdbcTemplate==null) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
}
}
持久层实现类
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao{
/**
* 继承 :
* 继承了他的setget方法,因此在bean.xml中,配置需要些该类全限定路径。
* 注意:
* 继承JdbcDaoSupport 的方式,只能用于基于 XML的方式,注解用不了。
*/
public Account findAccountById(Integer id) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),id);
return accounts.isEmpty()?null:accounts.get(0);
}
public Account findAccountByName(String accountName) {
List<Account> accounts= super.getJdbcTemplate().query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()) {
return null;
}
if(accounts.size()>1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public List<Account> findAll() {
List<Account> accounts= super.getJdbcTemplate().query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
return accounts;
}
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
2、业务层
业务层接口
/**
* 账户的业务层方法
*/
public interface IAccountService {
/**
* 根据id查账户信息
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 转账
* @param sourceName
* @param targetName
* @param money
*/
void transfer(String sourceName,String targetName,float money);
List<Account> findAll();
}
业务层实现类
/**
* 账户的业务层实现类
* 事务的控制应该都在业务层
*/
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
return accountDao.findAll();
}
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
public void transfer(String sourceName, String targetName, float money) {
System.out.println("transfer开始执行");
//2.1根据名称查询转出账户--------------------------------------
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney()-money);
//2.4转入账户加钱
target.setMoney(target.getMoney()+money);
//2.5更新转出账户
accountDao.updateAccount(source);
//给出异常
int i=1/0;
//2.6更新转入账户-------------------------------------------------
accountDao.updateAccount(target);
}
}
3、实体类
/**
* 账户的实体类
*/
public class Account implements Serializable{
private Integer id;
private String name;
private float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
4、配置文件
bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置业务层 -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置账户的持久层 -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy?useSSL=false&serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency><!-- 为了解析切入点表达式 -->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
5、测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testFindAll() {
List<Account> accounts = as.findAll();
for(Account account:accounts) {
System.out.println(account);
}
}
@Test
public void testTransfer() {
as.transfer("aaa", "bbb", 100.0f);
}
}
二、转账案例:基于xml的声明事务控制
1、持久层
持久层接口
public interface IAccountDao {
/**
* 根据id查询用户
* @param id
* @return
*/
Account findAccountById(Integer id);
Account findAccountByName(String accountName);
List<Account> findAll();
void updateAccount(Account source);
}
持久层实现类
继承JdbcDaoSupport 的方式,只能用于基于 XML的方式,注解用不了。
import org.springframework.jdbc.core.support.JdbcDaoSupport;
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao{
/**
* 继承 :
* 继承了他的setget方法,因此在bean.xml中,配置需要些该类全限定路径。
* 注意:
* 继承JdbcDaoSupport 的方式,只能用于基于 XML的方式,注解用不了。
*/
public Account findAccountById(Integer id) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),id);
return accounts.isEmpty()?null:accounts.get(0);
}
public Account findAccountByName(String accountName) {
List<Account> accounts= super.getJdbcTemplate().query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()) {
return null;
}
if(accounts.size()>1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public List<Account> findAll() {
List<Account> accounts= super.getJdbcTemplate().query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
return accounts;
}
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
2、业务层
业务层接口
/**
* 账户的业务层方法
*/
public interface IAccountService {
/**
* 根据id查账户信息
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 转账
* @param sourceName
* @param targetName
* @param money
*/
void transfer(String sourceName,String targetName,float money);
List<Account> findAll();
}
业务层实现类
/**
* 账户的业务层实现类
* 事务的控制应该都在业务层
*/
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
return accountDao.findAll();
}
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
public void transfer(String sourceName, String targetName, float money) {
System.out.println("transfer开始执行");
//2.1根据名称查询转出账户--------------------------------------
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney()-money);
//2.4转入账户加钱
target.setMoney(target.getMoney()+money);
//2.5更新转出账户
accountDao.updateAccount(source);
//给出异常
// int i=1/0;
//2.6更新转入账户-------------------------------------------------
accountDao.updateAccount(target);
}
}
3、实体类
/**
* 账户的实体类
*/
public class Account implements Serializable{
private Integer id;
private String name;
private float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
4、配置文件
bean.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">
<!-- 配置业务层 -->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置账户的持久层 -->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy?useSSL=false&serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- spring中基于XML的声明事务控制配置配置
1、配置事务管理器
2、配置事务的通知
此时我们需要导入事务的约束,tx的名称空间和约束,同时也需要aop的(data-access xmlns:tx)
使用tx:Advice标签配置事务通知
属性:
id:给事务通知起一个唯一标识。
transactionManager:给事务通知提供一个事务管理器引用
3、配置AOP中的通用切入点表达式
4、建立切入点表达式和事务通知的对应关系
5、配置事务的属性
是在事务的通知tx:advice标签内部
配置使用 tx:method 属性:name为方法名,后边是事务
<tx:method name="transfer" read-only="false"/>
优先级:"*">"find*"
isolation="DEFAULT"
//指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
propagation="REQUIRED"
//用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择,查询方法可以选择SUPPORTS
read-only="false"
//用于指定事务是否只读。只有查询方法才能设置为true。默认值为false,表示读写。
timeout="-1"
//用于指定事务的超时时间,默认值为-1,表示永不超时。如果指定了数值,以秒为单位。
no-rollback-for=""
//用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
rollback-for=""
//用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚。
-->
<!-- 1、配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 2、配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 5、配置事务的属性 -->
<tx:method name="*" read-only="false"/><!--优先级:"*">"find*" -->
<tx:method name="find*" read-only="true"/><!-- 遵守命名规则,查询方法以find开始 -->
</tx:attributes>
</tx:advice>
<!-- 配置AOP -->
<aop:config>
<!-- 3、配置切入点表达式 -->
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
<!--4、建立切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency><!-- 为了解析切入点表达式 -->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
5、测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testFindAll() {
List<Account> accounts = as.findAll();
for(Account account:accounts) {
System.out.println(account);
}
}
@Test
public void testTransfer() {
as.transfer("aaa", "bbb", 100.0f);
}
}
三、转账案例:基于注解的声明事务控制
1、持久层
持久层接口
public interface IAccountDao {
/**
* 根据id查询用户
* @param id
* @return
*/
Account findAccountById(Integer id);
Account findAccountByName(String accountName);
List<Account> findAll();
void updateAccount(Account source);
}
持久层实现类
继承JdbcDaoSupport
的方式,只能用于基于 XML的方式,注解用不了。
因此需要在bean中配置。
/**
* 账户的持久层实现类
*/
@Repository("accountDao")
//public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao{
public class AccountDaoImpl implements IAccountDao{
/**
* 继承 :
* 继承了他的setget方法,因此在bean.xml中,配置需要些该类全限定路径。
* 注意:
* 继承JdbcDaoSupport 的方式,只能用于基于 XML的方式,注解用不了。
*/
@Autowired
private JdbcTemplate jdbcTemplate;
public Account findAccountById(Integer id) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),id);
return accounts.isEmpty()?null:accounts.get(0);
}
public Account findAccountByName(String accountName) {
List<Account> accounts= jdbcTemplate.query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()) {
return null;
}
if(accounts.size()>1) {
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public List<Account> findAll() {
List<Account> accounts= jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
return accounts;
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
2、业务层
业务层接口
/**
* 账户的业务层方法
*/
public interface IAccountService {
/**
* 根据id查账户信息
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 转账
* @param sourceName
* @param targetName
* @param money
*/
void transfer(String sourceName,String targetName,float money);
List<Account> findAll();
}
业务层实现类
/**
* 账户的业务层实现类
* 事务的控制应该都在业务层
*
*/
@Service("accountService")
//配置在此处,范围全部方法(只读型事务配置)
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class AccountServiceImpl implements IAccountService{
@Autowired//可以去掉相对应的setget方法
private IAccountDao accountDao;
public List<Account> findAll() {
return accountDao.findAll();
}
public Account findAccountById(Integer id) {
return accountDao.findAccountById(id);
}
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
//范围此方法
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void transfer(String sourceName, String targetName, float money) {
System.out.println("transfer开始执行");
//2.1根据名称查询转出账户--------------------------------------
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney()-money);
//2.4转入账户加钱
target.setMoney(target.getMoney()+money);
//2.5更新转出账户
accountDao.updateAccount(source);
//给出异常
int i=1/0;
//2.6更新转入账户-------------------------------------------------
accountDao.updateAccount(target);
}
}
3、实体类
/**
* 账户的实体类
*/
public class Account implements Serializable{
private Integer id;
private String name;
private float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
}
}
4、配置文件
bean.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"
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/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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--
1、改ioc的注解:需要导入context的名称空间,以及它对应的约束
名称空间:xmlns:context="http://www.springframework.org/schema/context"
相对应的约束:http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
-->
<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="com.itheima"></context:component-scan>
<!-- 配置JdbcTemplate -->
<bean id="jcbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy?useSSL=false&serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- spring中基于注解的声明事务控制配置配置
1、配置事务管理器
2、开启spring对注解事务的支持
3、在需要事务支持的地方使用@Transactional注解
位置:方法和类都可以 作用范围不同。
-->
<!-- 1、配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 2.开启spring对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency><!-- 为了解析切入点表达式 -->
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
5、测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testFindAll() {
List<Account> accounts = as.findAll();
for(Account account:accounts) {
System.out.println(account);
}
}
@Test
public void testTransfer() {
as.transfer("aaa", "bbb", 100.0f);
}
}