文章目录
1、回顾事务
- 把一组业务当成一个业务来做;要么都成功,要么都失败。
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题,不能马虎。
- 确保完整性和一致性。
事务ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏。
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化的写到存储器中。
2、spring的事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中进行事务的管理。
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况下。
- 如果我们不在spring中配置声明式事务,我们就需要在代码中手动配事务。
- 事务在项目的开发中是十分重要的,设计到数据的一致性和完成性问题,不容马虎。
3、Spring事务的种类
spring支持编程式事务
管理和声明式事务
管理两种方式:
①编程式事务管理使用TransactionTemplate。
②声明式事务管理建立在AOP之上
的。其本质是通过AOP功能,对方法前后进行拦截,将事务处理的功能编织到拦截的方法中,也就是在目标方法开始之前加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。
声明式事务最大的优点就是不需要在业务逻辑代码中掺杂事务管理的代码,只需在配置文件中做相关的事务规则声明或通过@Transactional
注解的方式,便可以将事务规则应用到业务逻辑中。
声明式事务管理要优于编程式事务管理,这正是spring倡导的非侵入式的开发方式,使业务代码不受污染,只要加上注解就可以获得完全的事务支持。唯一不足地方是,最细粒度只能作用到方法级别,无法做到像编程式事务那样可以作用到代码块级别。
4、基于XML的事务配置
1. 使用说明
基于XML的声明式事务控制配置步骤:
1、配置事务管理器
2、配置事务的通知
此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的。
使用tx:advice标签配置事务通知。
属性:
- id:给事务通知起一个唯一标识
- transaction-manager:给事务通知提供一个事务管理器引用。
3、配置AOP中的通用切入点表达式
4、建立事务通知和切入点表达式的对应关系
5、配置事务的属性
是在事务的通知tx:advice标签的内部。
配置事务的属性:
- isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
- propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
- read-only:用于指定事务是否只读。只查询方法才能设置为true。默认值是false,表示读写。
- timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
- rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
- no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
Propagation类的事务属性:七种
- REQUIRED:支持当前事務,如果当前没有事务,就新建一个事務。 这是最常见的选择。默认
- SUPPORTS:持当前事務,如果当前没有事务,就以非务方式执行。
- MANDATORY:支持当前事务,如果当前没有務,就抛出异常。
- REQUIRES_ NEW:新建事务,如果当前存在事务,把当前事务挂起。
- NOT_ _SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- NEVER:以啡事務方式执行,如果当前存在務,则抛出异常。
- NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。
2. 代码如下
配置文件
<?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.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置aop-->
<aop:config>
<!-- 配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
持久层
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
public Account findAccountById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
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 void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
业务层
/**
* 账户的业务层实现类
*
* 事务控制应该都是在业务层
*/
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
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);
}
}
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test1 {
@Autowired
private IAccountService service;
@Test
public void test1(){
service.transfer("aaa","bbb",1000f);
}
}
5、基于注解的事务配置
1. 使用说明
基于注解的声明式事务控制配置步骤:
1、配置事务管理器
2、开启spring对注解事务的支持
3、在需要事务支持的地方使用 @Transactional注解(业务层的实现)
事务声明注解:该注解可以添加到类或者方法上。
属性:
- propagation:用来设置事务的传播行为:一个方法运行在一个开启了事务的方法中,当前方法是使用原有的事务还是开启新事物。
- required:如果有事务就使用,没有就开启一个新的(默认)
- required_new:必须开启新事物
- supports:如果有事务就运行,否则也不开启新的事务
- no_supports:即使有事务也不用
2. 代码如下
配置文件
<?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: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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.itheima"></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/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置事务管理器 -->
<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>
持久层
/**
* 账户的持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
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);
}
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 void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
业务层
/**
* 账户的业务层实现类
*
* 事务控制应该都是在业务层
*/
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true) //只读型事物的配置
public class AccountServiceImpl implements IAccountService{
@Autowired
private IAccountDao accountDao;
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
//需要的是读写型事务配置
@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);
}
}
测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test1 {
@Autowired
private IAccountService service;
@Test
public void test1(){
service.transfer("aaa","bbb",1000f);
}
}
6、基于XML和注解的事务配置
代码如下
jdbcConfig.xml
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/eesy
jdbc.username=root
jdbc.password=123456
JdbcConfig类
/**
* 和链接数据库相关的配置类
*/
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建JdbcTemplate
* @param dataSource
* @return
*/
@Bean(name = "jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
/**
* 创建数据库对象
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
SpringConfiguration类
/**
* spring的配置类,相当于bean.xml
*/
@Configuration
@ComponentScan("com.itheima")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement//开启spring对注解事务的支持
public class SpringConfiguration {
}
TransactionConfig类
/**
* 和事务相关的配置类
*/
public class TransactionConfig {
/**
* 用于创建事务管理器对象
* @param dataSource
* @return
*/
@Bean(name = "transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
业务层
/**
* 账户的业务层实现类
*
* 事务控制应该都是在业务层
*/
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true) //只读型事物的配置
public class AccountServiceImpl implements IAccountService{
@Autowired
private IAccountDao accountDao;
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
//需要的是读写型事务配置
@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);
}
}
持久层
/**
* 账户的持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
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);
}
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 void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
测试类
/**
* 使用Junit单元测试:测试我们的配置
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private IAccountService as;
@Test
public void testTransfer(){
as.transfer("aaa","bbb",100f);
}
}
7、@Transactional详细介绍
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class}, isolation = Isolation.DEFAULT, readOnly = false)
1. Spring的事务传播行为
spring事务的传播行为说的是,当多个事务同时存在的时候,spring如何处理这些事务的行为。
① PROPAGATION_REQUIRED:如果当前没有事务,就创建一个新事务,如果当前存在事务,就加入该事务,该设置是最常用的设置。
② PROPAGATION_SUPPORTS:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就以非事务执行。
③ PROPAGATION_MANDATORY:支持当前事务,如果当前存在事务,就加入该事务,如果当前不存在事务,就抛出异常。
④ PROPAGATION_REQUIRES_NEW:创建新事务,无论当前存不存在事务,都创建新事务。
⑤ PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
⑥ PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
⑦ PROPAGATION_NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则按REQUIRED属性执行。
2. Spring中的隔离级别
① ISOLATION_DEFAULT:这是个 PlatfromTransactionManager 默认的隔离级别,使用数据库默认的事务隔离级别。
② ISOLATION_READ_UNCOMMITTED:读未提交,允许另外一个事务可以看到这个事务未提交的数据。
③ ISOLATION_READ_COMMITTED:读已提交,保证一个事务修改的数据提交后才能被另一事务读取,而且能看到该事务对已有记录的更新。
④ ISOLATION_REPEATABLE_READ:可重复读,保证一个事务修改的数据提交后才能被另一事务读取,但是不能看到该事务对已有记录的更新。
⑤ ISOLATION_SERIALIZABLE:一个事务在执行的过程中完全看不到其他事务对数据库所做的更新。
8、JdbcTemplate的使用
1. 说明
1.增删改
JdbcTemplate.update(String, Object...)
2.批量增删改
JdbcTemplate.batchUpdate(String, List<Object[]>)
Object[]封装了 SQL 语句每一次执行时所需要的参数
List 集合封装了 SQL 语句多次执行时的所有参数
3.查询单行
JdbcTemplate.queryForObject(String, RowMapper<Department>, Object...)
4.查询多行
JdbcTemplate.query(String, RowMapper<Department>, Object...)
RowMapper 对象依然可以使用 BeanPropertyRowMapper
5.查询单一值
JdbcTemplate.queryForObject(String, Class, Object...)
2. 代码如下
<!-- 引入外部配置文件 -->
<context:property-placeholder location="classpath:druid.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${driverClassName}"></property>
<property name="initialSize" value="${initialSize}"></property>
<property name="maxActive" value="${maxActive}"></property>
</bean>
<!-- 配置jdbcTemplate -->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 设置dateSource属性 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置NamedParameterJdbcTemplate -->
<bean id="NamedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<!-- 设置自动扫描的包 -->
<context:component-scan base-package="com.qf"></context:component-scan>
//获取jdbctemplate对象
JdbcTemplate jdbcTemplate=(JdbcTemplate) ioc.getBean("JdbcTemplate");
//通用增删改
@Test
public void test2() {
String sql="insert into user(id,username,password,tel,sex,vip)values(?,?,?,?,?,?);";
jdbcTemplate.update(sql,5,"白洁","baijie","110","女",0);
}
//批处理
@Test
public void test3() {
String sql="insert into user(id,username,password,tel,sex,vip)values(?,?,?,?,?,?);";
List<Object[]> batchArgs=new ArrayList<Object[]>();
batchArgs.add(new Object[] {6,"张敏","zhangmin","110","女",1});
batchArgs.add(new Object[] {7,"美红","meihong","110","女",1});
batchArgs.add(new Object[] {8,"阿悄","aqiao","110","女",1});
jdbcTemplate.batchUpdate(sql, batchArgs);
}
//获取单一值的方法
@Test
void test4() {
String sql="select count(*) from user;";
Integer count=jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println(count);
}
//获取一个对象的方法
@Test
void test2() {
String sql="select id,username,password from user where id=?;";
RowMapper<User> rowMapper= new BeanPropertyRowMapper<>(User.class);
User user=jdbcTemplate.queryForObject(sql, rowMapper, 7);
System.out.println(user);
}
//获取一个对象集合的方法
@Test
void test2() {
String sql="select id,username,password from user;";
RowMapper<User> rowMapper= new BeanPropertyRowMapper<>(User.class);
List<User> list=jdbcTemplate.query(sql, rowMapper);
for(User user:list) {
System.out.println(user);
}
}
-----------------------------------
//获取NamedParameterJdbcTemplate对象
NamedParameterJdbcTemplate npjt=
(NamedParameterJdbcTemplate)ioc.getBean("NamedParameterJdbcTemplate");
//通过NamedParameterJdbcTemplate操作带具名参数的sql方法一:
@Test
void test2() {
String sql="insert into user(id,username,password)values(:id,:username,:password);";
Map<String, Object> map=new HashMap<String, Object>();
map.put("id", 10);
map.put("username","zhansan");
map.put("password", "123");
npjt.update(sql, map);
}
//通过NamedParameterJdbcTemplate操作带具名参数的sql方法二:
void test2() {
String sql="insert into user(id,username,password)values(:id,:username,:password);";
User user=new User();
user.setId(10);
user.setUsername("lisi");
user.setPassword("123");
SqlParameterSource parameterSource=new BeanPropertySqlParameterSource(user);
npjt.update(sql, parameterSource);
}
-----------------------------------
//通过NamedParameterJdbcTemplate实现获取所有员工
@Repository("userdaoimpl")
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<User> getUser() {
String sql="select id,username,password from user;";
//创建RowMapper对象
RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class);
List<User> users=jdbcTemplate.query(sql, rowMapper);
return users;
}
}
@Service("userserviceimpl")
public class UserServiceimpl implements UserService{
@Autowired
private UserDao userdao;
@Override
public List<User> getUsers() {
return userdao.getUser();
}
}
@Test
//通过NamedParameterJdbcTemplate实现获取所有员工
void test2() {
UserService userService=(UserService) ioc.getBean("userserviceimpl");
List<User> users=userService.getUsers();
for(User user:users) {
System.out.println(user);
}
}
链接: 对Spring深入的理解 | 概念的总结
链接: Spring IOC详解
链接: Spring 依赖注入详解
链接: Spring AOP详解
如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客