spring事务
事务的概念
数据库操作的最基本单元,逻辑上的一组操作,要么都成功,要么都失败。场景:转账时转出方和转入方的金额变化要么都成功,要么都失败,不能只成功一部分。
事务的四个特性(acid)
1、原子性(Atomicity)
事务内的所有操作要么全部成功,要么全部都不成功。
示例:A转账100给B,则A的账户减少100,B的账户增加100,结果只能是A减少了100并且B增加了100,或者A和B都没有变化,不可能A减少了B没有增加或者A没有减少但是B增加了。
2、一致性(Consistency)
事务必须使数据库从一个一致性状态变换到另一个一致性状态,数据库的完整性约束没有被破坏,也就是说一个事务执行之前和执行之后都必须处于一致性状态。
示例:A和B一共拥有1000元钱,则无论A和B之间如何转账,转多少次,最终事务完成之后A和B的钱加起来都是1000。
3、隔离性(Isolation)
一个事务的执行不能被其他事务干扰,即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
示例:A正在给B转钱,这时C也要给B转钱,这时C要么在A转完钱之前给B转,要么在A转完钱之后给B转钱,不能两个同时发生。
4、持久性(Durability)
一个事务一旦提交,则它对数据库的数据的影响是永久的,提交之后的操作或者有什么故障都不会对其造成影响
示例:A在给B转完钱之后,就算是数据库服务此时down机了,这个修改也会保存下来。
spring的事务管理操作
编程式事务管理
UserDao
package com.example.demo.dao;
import java.util.List;
public interface UserDao {
void incrOne();
}
UserDaoImpl
package com.example.demo.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import javax.sql.DataSource;
import java.util.List;
public class UserDaoImpl implements UserDao{
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
private PlatformTransactionManager transactionManager;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
public void incrOne() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(definition);
try {
String sql1 = "update user set money = money-100 where id = ?";
String sql2 = "update user set money = money+100 where id = ?";
int i = jdbcTemplate.update(sql1, 4);
int j = jdbcTemplate.update(sql2, 5);
transactionManager.commit(status);
if (i == 1) {
System.out.println(4 + " 号扣除成功!!");
}
if (j == 1) {
System.out.println(5 + " 号增加成功!!");
}
} catch (Exception e) {
transactionManager.rollback(status);
e.printStackTrace();
}
}
}
bean1.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--引入配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置jdbcTemplate-->
<bean id="userDaoImpl" class="com.example.demo.dao.UserDaoImpl">
<property name="dataSource" ref="dataSource"/>
<property name="transactionManager" ref="transactionManager"/>
</bean>
</beans>
MyTest
package com.example.demo;
import com.example.demo.dao.UserDaoImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void testJdbc() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserDaoImpl userDao = context.getBean("userDaoImpl", UserDaoImpl.class);
userDao.incrOne();
}
}
执行结果
如果发生异常
UserDaoImpl
package com.example.demo.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import javax.sql.DataSource;
import java.util.List;
public class UserDaoImpl implements UserDao{
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
private PlatformTransactionManager transactionManager;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
public void incrOne() {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(definition);
try {
String sql1 = "update user set money = money-100 where id = ?";
String sql2 = "update user set money = money+100 where id = ?";
int i = jdbcTemplate.update(sql1, 4);
int k = 10 / 0;
int j = jdbcTemplate.update(sql2, 5);
transactionManager.commit(status);
if (i == 1) {
System.out.println(4 + " 号扣除成功!!");
}
if (j == 1) {
System.out.println(5 + " 号增加成功!!");
}
} catch (Exception e) {
transactionManager.rollback(status);
e.printStackTrace();
}
}
}
执行结果
声明式事务管理
基于注解方式
UserDao
package com.example.demo.dao;
import java.util.List;
public interface UserDao {
void incrOne();
void decrOne();
}
UserDaoImpl
package com.example.demo.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class UserDaoImpl implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void incrOne() {
String sql = "update user set money = money-100 where id = ?";
int i = jdbcTemplate.update(sql, 4);
if (i == 1) {
System.out.println(4 + " 号扣除成功!!");
}
}
@Override
public void decrOne() {
String sql = "update user set money = money+100 where id = ?";
int i = jdbcTemplate.update(sql, 5);
if (i == 1) {
System.out.println(5 + " 号增加成功!!");
}
}
}
在Service类上加上@Transactional注解
package com.example.demo.service;
import com.example.demo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserService{
@Autowired
private UserDao userDao;
public void transferMoney() {
userDao.decrOne();
int a = 10/0;
userDao.incrOne();
}
}
bean1.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.example.demo"/>
<!--引入配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据库连接池-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<!--配置jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"/>
</bean>
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
</beans>
要添加tx命名空间,否则没有tx标签,或者会报XmlBeanDefinitionStoreException异常
MyTest
package com.example.demo;
import com.example.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void testJdbc() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService service = context.getBean("userService", UserService.class);
service.transferMoney();
}
}
执行结果
金额并无变化
如果出现使用了注解但是金额还是变化了可以参考这篇文章 @Transactional注解失效
基于配置文件方式
UserService
package com.example.demo.service;
import com.example.demo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void transferMoney(){
userDao.decrOne();
int a = 10/0;
userDao.incrOne();
}
}
bean1.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--组件扫描-->
<context:component-scan base-package="com.example.demo"/>
<!--引入配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据库连接池-->
<bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<!--配置jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="datasource"/>
</bean>
<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<!--配置通知(增强)-->
<tx:advice id="txAdvice">
<!--配置事务-->
<tx:attributes>
<!--配置哪些方法添加事务,此处为transferMoney方法-->
<tx:method name="transferMoney"/>
</tx:attributes>
</tx:advice>
<!--配置切入点和切面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="p" expression="execution(* com.example.demo.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="p"/>
</aop:config>
</beans>
执行结果