Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use spring Framework to implement Database transaction processing

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use the spring framework to achieve database transaction processing, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Using spring Framework to realize Database transaction processing

For a database, a transaction is a series of operations on sql statements that are organized into a transaction. If the transaction is atomic, it is either executed or not executed. If there is an error in the sql statement in the transaction, the transaction needs to roll back the sql that has been executed, undo the previous operation on the database, and prevent the database from appearing an error state.

JDBC's support for database transaction processing

Jdbc itself provides support for database processing, using java.sql.Connection objects to commit transactions. Commit the database transaction using Connection as follows:

It is found that there is a method called setAutoCommit (). When set to true, sql is automatically submitted. If set to false, the sql statement is submitted by the program, and the application must call the Commit method. At the same time, the rollback method is called in the exception handling block of the execution sql statement to roll back the database before the exception occurs.

At the enterprise level, transactions are generally executed concurrently. When transactions are executed concurrently, the problem of database synchronization occurs. The specific problems can be divided into the following four types:

Dirty reading:

Cannot be read repeatedly:

Missing updates:

Illusory reading:

In order to solve the above four problems, to solve the problem of transaction concurrency

JDBC defines five transaction isolation levels to solve these concurrency problems.

Transaction_read_uncommitted: the lowest level of data, commonly known as dirty reading, has already read the updated data when the data is not submitted.

Transaction_read_committed: when a transaction makes a query, it is allowed to read the data before the commit. After the data is submitted, the current query can read the data, and the table is not locked when update data. (longest use)

Transaction_repeatable_read: when a transaction is querying, it is not allowed to read the data updated by other transactions, but can read the new data from other transactions.

Transaction_serializable: when a transaction is querying, no query is allowed for the transaction, which means changing parallel to serial. It is not recommended to use.

Invoking a database transaction in the spring framework takes three steps:

The first step is to configure the data source is to configure the name and password of the database, address and so on.

The second step is to declare that the transaction management TransactionManagerspring framework provides PlatformTransactionManager as the top-level interface of the transaction management class, declaring interfaces for initializing transactions, committing transactions, rolling back transactions, and so on. The interface implementation is implemented by a specific database-driven class. It includes DataTransactionManager and other implementation classes. But the DataTransactionManager class is mainly used.

The DAO class DAO, which defines that transactions can be performed, provides the necessary interfaces and methods for applications to access data sources.

What are the ways to implement spring transactions

Programmatic transaction management

Call commit (), rollback () and other transaction management related methods in the code

Maven pom.xml file

Org.springframework spring-beans 4.2.4.RELEASE org.springframework spring-context 4.2.4.RELEASE org.springframework spring-aop 4.2.4.RELEASE org.springframework spring-tx 4.2.4.RELEASE org.springframework spring-jdbc 4.2.4.RELEASE mysql mysql-connector-java 5.1.18

Programmatic transaction management, which can control transactions through java.sql.Connection. Spring profile

Jdbc:mysql://localhost:3306/test root root

Test code

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 () / / Test functional control transaction} 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) / / initialize table conn.setAutoCommit (false); / / set not to automatically commit transactions queryUsers (conn); / / query print user table deleteUser (conn); / / delete id=1 user conn.rollback (); / / roll back queryUsers (conn) / query the print user table} 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") / / whether transactions are supported or not depends on the database engine. Deleting ENGINE=InnoDB DEFAULT CHARSET=utf8 here may not support transactions 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 () }

Delete user statement rollback and print out two users

1 user1

2 user2

1 user1

2 user2

Declarative transaction Management of TransactionProxyFactoryBean

New UserDao API

Package constxiong.interview.transaction; import java.util.List;import java.util.Map; public interface UserDao {/ * query user * @ return * / public List getUsers (); / * Delete user * @ param id * @ return * / public int deleteUser (int id);}

New UserDao implementation

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 {/ * query user * @ return * / public List getUsers () {String sql = "select * from user"; return this.getJdbcTemplate () .queryForList (sql) } / * * Delete user * @ 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;}}

Modify the spring configuration file to add transaction manager DataSourceTransactionManager and transaction agent class TransactionProxyFactoryBean

Jdbc:mysql://localhost:3306/test root root -java.lang.RuntimeException

Test code

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 () / / Test using spring TransactionProxyFactoryBean} private static void testUseTransactionProxy () {final UserDao userDao = (UserDao) context.getBean ("userProxy"); printUsers (userDao); / / print user userDao.deleteUser (1) / / Delete id=1 user} private static void printUsers (UserDao userDao) {for (Map user: userDao.getUsers ()) {System.out.println (user);}

Result output

{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 (NativeMethod)

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)

Declarative transaction management for annotated @ Transactional

UserDaoImpl delete user method add comment @ Transactional (rollbackFor=RuntimeException.class) RuntimeException rollback occurs

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 {/ * query user * @ return * / public List getUsers () {String sql = "select * from user" Return this.getJdbcTemplate () .queryForList (sql);} / * * Delete user * @ 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;}}

Modify the spring configuration file to enable spring's transaction annotation capability

Jdbc:mysql://localhost:3306/test root root

Test code

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 user: userDao.getUsers ()) {System.out.println (user);}

Output result

{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 (NativeMethod)

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 configuration (comment) transaction

Maven pom.xml adds support for Aspectj

Org.aspectj aspectjweaver 1.8.13

Remove the UserDaoImpl annotation @ 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 implements UserDao {/ * query user * @ return * / public List getUsers () {String sql = "select * from user"; return this.getJdbcTemplate () .queryForList (sql) } / * * Delete user * @ 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;}}

Modify the spring configuration file to weave into the section

Jdbc:mysql://localhost:3306/test root root

Test code

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 user: userDao.getUsers ()) {System.out.println (user);}

Output result

{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 (NativeMethod)

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)

Thank you for reading this article carefully. I hope the article "how to use spring framework to achieve database transaction processing" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report