spring基于注解的声明式事务控制
1.打开IDEA的界面如图所示:点击Create New Project.
2.选择Maven工程和JDK的版本,并点击Next。如图所示:
3.填写项目名称和保存的地址,如图所示。点击Finish。
4.导入相应依赖jar包的代码如下:
<?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>ccm.txw</groupId>
<artifactId>day04_06tx_anno</artifactId>
<version>1.0-SNAPSHOT</version>
<!--打包的方式-->
<packaging>jar</packaging>
<dependencies>
<!--导入spring-context的依赖jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--导入spring-jdbc的依赖jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--导入的依赖jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--导入mysql的依赖jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--导入aspectjweaver的依赖jar包-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<!--导入的lombok依赖jar包-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--导入spring-testb的依赖jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!--导入junit的依赖jar包-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
5.创建账户的实体类代码如下:
package com.txw.domain;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 账户的实体类
* @author Adair
*/
@Data // 自动生成set和get方法
@ToString // 重写toString方法
@SuppressWarnings("all") // 注解警告信息
public class Account implements Serializable {
private Integer id; // 账户的id
private String name; // 账户的名称
private Float money; // 账户的余额
}
6.创建持久层接口的代码如下:
package com.txw.dao;
import com.txw.domain.Account;
/**
* 账户的持久层接口
* @author Adair
*/
@SuppressWarnings("all") // 注解警告信息
public interface IAccountDao {
/**
* 根据Id查询账户
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 根据名称查询账户
* @param accountName
* @return
*/
Account findAccountByName(String accountName);
/**
* 更新账户
* @param account
*/
void updateAccount(Account account);
}
7.创建持久层的实现类的代码如下:
package com.txw.dao.impl;
import com.txw.dao.IAccountDao;
import com.txw.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 账户的持久层实现类
* @author Adair
*/
@SuppressWarnings("all") // 注解警告信息
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
// 声明JdbcTemplate业务对象
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 根据Id查询账户
* @param accountId
* @return
*/
public Account findAccountById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
return accounts.isEmpty()?null:accounts.get(0);
}
/**
* 根据名称查询账户
* @param accountName
* @return
*/
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);
}
/**
* 更新账户
* @param account
*/
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
8.创建业务层接口的代码如下:
package com.txw.service;
import com.txw.domain.Account;
/**
* 账户的业务层接口
* @author Adair
*/
@SuppressWarnings("all") // 注解警告信息
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);
}
9.创建业务层的实现类的代码如下:
package com.txw.service.impl;
import com.txw.dao.IAccountDao;
import com.txw.domain.Account;
import com.txw.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* 账户的业务层实现类
* 事务控制应该都是在业务层
* @author Adair
*/
@SuppressWarnings("all") // 注解警告信息
@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService{
// 声明IAccountDao业务对象
@Autowired
private IAccountDao accountDao;
/**
* 根据id查询账户信息
* @param accountId
* @return
*/
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
/**
* 转账
* @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....");
// 根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
// 根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
// 转出账户减钱
source.setMoney(source.getMoney()-money);
// 转入账户加钱
target.setMoney(target.getMoney()+money);
// 更新转出账户
accountDao.updateAccount(source);
int i = 1 / 0;
// 更新转入账户
accountDao.updateAccount(target);
}
}
10.在resource目录创建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">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.txw"></context:component-scan>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" 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.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- spring中基于注解 的声明式事务控制配置步骤
1、配置事务管理器
2、开启spring对注解事务的支持
3、在需要事务支持的地方使用@Transactional注解
-->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
11.测试类的代码如下:
package com.txw.test;
import com.txw.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* 使用Junit单元测试:测试我们的配置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
// 声明IAccountService业务对象
@Autowired
private IAccountService as;
/**
* 测试转账
*/
@Test
public void testTransfer(){
as.transfer("aaa","bbb",100f);
}
}