多平台统一管理软件接口,如何实现多平台统一管理软件接口
231
2022-09-24
使用spring框架实现数据库事务处理方式
目录使用spring框架实现数据库事务处理JDBC对数据库事务处理的支持JDBC定义了五种事务隔离级别来解决这些并发导致的问题在spring框架中调用一个数据库事务处理分三步走:spring 事务实现方式有哪些在代码中调用 commit()、rollback()等事务管理相关的方法TransactionProxyFactoryBean 的声明式事务管理注解 @Transactional 的声明式事务管理Aspectj AOP 配置(注解)事务
使用spring框架实现数据库事务处理
事务对于数据库来说是,是对sql语句的一系列操作,这些操作被组织成为一个事务。事务具有原子性的,要么全部执行,要么不执行。若事务中sql语句发生错误,事务需要对已经执行的sql进行回滚操作,撤销先前对数据库的操作,防止数据库出现错误状态。
JDBC对数据库事务处理的支持
jdbc本身提供了对数据库处理的支持,使用java.sql.Connection对象完成事务的提交。使用Connection提交数据库事务处理如下:
发现里面有一个方法叫setAutoCommit(),设置为true时,就是自动提交sql,如果设置为false时,sql语句的提交由程序负责,应用程序必须调用Commit方法,同时在执行sql语句异常处理块中调用rollback方法,对异常发生前进行的数据库进行回滚。
在企业级中,事务一般都是并发执行的,当事务并发执行时,就会发生数据库同步的问题,具体问题可分为下面四种类型:
脏读:
不可重复读:
丢失更新:
幻读:
为了解决上面的四种问题,解决事务并发的问题
JDBC定义了五种事务隔离级别来解决这些并发导致的问题
transaction_read_uncommitted:数据级别最低,俗称脏读,在没有提交数据时,就已经读取到已经更新的数据。
transaction_read_committed:当一个事务进行查询时,允许读取提交前的数据,数据提交后,当前查询就可以读取到数据,update数据的时候并不锁住表。(最长使用)
transaction_repeatable_read:当一个事务进行查询时,不允许读取其他事务更新的数据,可以读取其他事务新增的数据。
transaction_serializable:当一个事务进行查询时,不允许任何对这个事务进行查询,就是把并行改成了串行。不提倡使用。
在spring框架中调用一个数据库事务处理分三步走:
第一步就是配置数据源就是配置数据库的名称和密码,地址等。
第二步就是声明事务管理TransactionManagerspring框架提供了PlatformTransactionManager作为事务管理类的顶层接口,声明了初始化事务,提交事务,回滚事务等接口。接口实现由具体的数据库驱动类实现。具体包括DataTransactionManager等实现类。但是主要还是使用的是DataTransactionManager类。
spring 事务实现方式有哪些
编程式事务管理,
在代码中调用 commit()、rollback()等事务管理相关的方法
maven pom.xml文件
编程式事务管理,可以通过 java.sql.Connection 控制事务。spring 配置文件
xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context" xsi:schemaLocation=" http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd">
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:context="http://springframework.org/schema/context"
xsi:schemaLocation="
http://springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans.xsd
http://springframework.org/schema/context
http://springframework.org/schema/context/spring-context.xsd">
测试代码
package constxiong.interview.transaction;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TransactionTest {
public static void main(String[] args) throws Exception {
testManualTransaction();//测试函数式控制事务
}
private static void testManualTransaction() throws SQLException {
ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");
DataSource ds = (DataSource)context.getBean("datasource");
Connection conn = ds.getConnection();
try {
initTable(conn);//初始化表
conn.setAutoCommit(false);//设置不自动提交事务
queryUsers(conn);//查询打印用户表
deleteUser(conn);//删除 id=1 用户
conn.rollback();//回滚
queryUsers(conn);//查询打印用户表
} finally {
conn.close();
}
}
private static void initTable(Connection conn) throws SQLException {
conn.createStatement().execute("drop table if exists user");
conn.createStatement().execute("create table user(id int, username varchar(60)) ENGINE=InnoDB DEFAULT CHARSET=utf8 ");//是否支持事务与数据库引擎有关,此处删除 ENGINE=InnoDB DEFAULT CHARSET=utf8 可能不支持事务
conn.createStatement().execute("insert into user values(1, 'user1')");
conn.createStatement().execute("insert into user values(2, 'user2')");
}
private static void deleteUser(Connection conn) throws SQLException {
conn.createStatement().execute("delete from user where id = 1");
}
private static void queryUsers(Connection conn) throws SQLException {
Statement st = conn.createStatement();
st.execute("select * from user");
ResultSet rs = st.getResultSet();
while (rs.next()) {
System.out.print(rs.getString("id"));
System.out.print(" ");
System.out.print(rs.getString("username"));
System.out.println();
}
}
}
删除用户语句回滚,打印出两个用户
1 user1
2 user2
1 user1
2 user2
TransactionProxyFactoryBean 的声明式事务管理
新增 UserDao 接口
package constxiong.interview.transaction;
import java.util.List;
import java.util.Map;
public interface UserDao {
/**
* 查询用户
* @return
*/
public List
/**
* 删除用户
* @param id
* @return
*/
public int deleteUser(int id);
}
新增 UserDao 实现
package constxiong.interview.transaction;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
/**
* 查询用户
* @return
*/
public List
String sql = "select * from user";
return this.getJdbcTemplate().queryForList(sql);
}
/**
* 删除用户
* @param id
* @return
*/
public int deleteUser(int id){
String sql = "delete from user where id = " + id;
int result = this.getJdbcTemplate().update(sql);
if (id == 1) {
throw new RuntimeException();
}
return result;
}
}
修改 spring 配置文件,添加事务管理器 DataSourceTransactionManager 和事务代理类 TransactionProxyFactoryBean
xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context" xsi:schemaLocation=" http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd">
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:context="http://springframework.org/schema/context"
xsi:schemaLocation="
http://springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans.xsd
http://springframework.org/schema/context
http://springframework.org/schema/context/spring-context.xsd">
测试代码
package constxiong.interview.transaction;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TransactionTest {
static ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");
public static void main(String[] args) throws Exception {
testUseTransactionProxy(); //测试使用 spring TransactionProxyFactoryBean
}
private static void testUseTransactionProxy() {
final UserDao userDao = (UserDao)context.getBean("userProxy");
printUsers(userDao);//打印用户
userDao.deleteUser(1);//删除 id=1 用户
}
private static void printUsers(UserDao userDao) {
for (Map
System.out.println(user);
}
}
}
结果输出
{id=1, username=user1}
{id=2, username=user2}
Exception in thread "main" java.lang.RuntimeException
at constxiong.interview.http://transaction.UserDaoImpl.deleteUser(UserDaoImpl.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy3.deleteUser(Unknown Source)
at constxiong.interview.transaction.TransactionTest.testUseTransactionProxy(TransactionTest.java:32)
at constxiong.interview.transaction.TransactionTest.main(TransactionTest.java:13)
注解 @Transactional 的声明式事务管理
UserDaoImpl 删除用户方法添加注解 @Transactional(rollbackFor=RuntimeException.class) 出现 RuntimeException 回滚
package constxiong.interview.transaction;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.transaction.annotation.Transactional;
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
/**
* 查询用户
* @return
*/
public List
String sql = "select * from user";
return this.getJdbcTemplate().queryForList(sql);
}
/**
* 删除用户
* @param id
* @return
*/
@Transactional(rollbackFor=RuntimeException.class)
public int deleteUser(int id){
String sql = "delete from user where id = " + id;
int result = this.getJdbcTemplate().update(sql);
if (id == 1) {
throw new RuntimeException();
}
return result;
}
}
修改 spring 配置文件,开启 spring 的事务注解能力
xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context" xmlns:tx="http://springframework.org/schema/tx" xsi:schemaLocation=" http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-3.2.xsd http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd"> <http://;/bean>
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:context="http://springframework.org/schema/context"
xmlns:tx="http://springframework.org/schema/tx"
xsi:schemaLocation="
http://springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans.xsd
http://springframework.org/schema/tx
http://springframework.org/schema/tx/spring-tx-3.2.xsd
http://springframework.org/schema/context
http://springframework.org/schema/context/spring-context.xsd">
<http://;/bean>
测试代码
package constxiong.interview.transaction;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TransactionTest {
static ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");
public static void main(String[] args) throws Exception {
testAnnotationTransaction();
}
private static void testAnnotationTransaction() {
UserDao userDao = (UserDao)context.getBean("userDao");
printUsers(userDao);
userDao.deleteUser(1);
}
private static void printUsers(UserDao userDao) {
for (Map
System.out.println(user);
}
}
}
输出结果
{id=1, username=user1}
{id=2, username=user2}
Exception in thread "main" java.lang.RuntimeException
at constxiong.interview.transaction.UserDaoImpl.deleteUser(UserDaoImpl.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy5.deleteUser(Unknown Source)
at constxiong.interview.transaction.TransactionTest.testAnnotationTransaction(TransactionTest.java:20)
at constxiong.interview.transaction.TransactionTest.main(TransactionTest.java:13)
Aspectj AOP 配置(注解)事务
maven pom.xml 添加 Aspectj 的支持
去除 UserDaoImpl 注解@Transactional(rollbackFor=RuntimeException.class)
package constxiong.interview.transaction;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class UserDaoImpl extends JdbcDaoSupport implHUisnSuements UserDao {
/**
* 查询用户
* @return
*/
public List
String sql = "select * from user";
return this.getJdbcTemplate().queryForList(sql);
}
/**
* 删除用户
* @param id
* @return
*/
public int deleteUser(int id){
String sql = "delete from user where id = " + id;
int result = this.getJdbcTemplate().update(sql);
if (id == 1) {
throw new RuntimeException();
}
return result;
}
}
修改 spring 配置文件,织入切面
xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context" xmlns:tx="http://springframework.org/schema/tx" xmlns:aop="http://springframework.org/schema/aop" xsi:schemaLocation=" http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans.xsd http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-3.2.xsd http://springframework.org/schema/aop http://springframework.org/schema/aop/spring-aop.xsd http://springframework.org/schema/context http://springframework.org/schema/context/spring-context.xsd">
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:context="http://springframework.org/schema/context"
xmlns:tx="http://springframework.org/schema/tx"
xmlns:aop="http://springframework.org/schema/aop"
xsi:schemaLocation="
http://springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans.xsd
http://springframework.org/schema/tx
http://springframework.org/schema/tx/spring-tx-3.2.xsd
http://springframework.org/schema/aop
http://springframework.org/schema/aop/spring-aop.xsd
http://springframework.org/schema/context
http://springframework.org/schema/context/spring-context.xsd">
测试代码
package constxiong.interview.transaction;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TransactionTest {
static ApplicationContext context = new ClassPathXmlApplicationContext("spring_transaction.xml");
public static void main(String[] args) throws Exception {
testAspectjTransaction();
}
private static void testAspectjTransaction() {
UserDao userDao = (UserDao)context.getBean("userDao");
printUsers(userDao);
userDao.deleteUser(1);
}
private static void printUsers(UserDao userDao) {
for (Map
System.out.println(user);
}
}
}
输出结果
{id=1, username=user1}
{id=2, username=user2}
Exception in thread "main" java.lang.RuntimeException
at constxiong.interview.transaction.UserDaoImpl.deleteUser(UserDaoImpl.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy2.deleteUser(Unknown Source)
at constxiong.interview.transaction.TransactionTest.testAnnotationTransaction(TransactionTest.java:20)
at constxiong.interview.transaction.TransactionTest.main(TransactionTest.java:13)
PS:
这篇仅用事务回滚为例,了解 spring 事务控制,还需要关注数据库的ACID四种特性、事务传播特性、事务的隔离级别(脏读、不可重复读、幻读)。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~