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 implement Spring JDBC transaction Management

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

Share

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

This article focuses on "how to achieve Spring JDBC transaction management", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to achieve Spring JDBC transaction management"!

JDBC transaction management

Spring provides programmatic transaction management (Programmatic transaction manage- ment) and declarative transaction management (Declarative transaction management), which provides a consistent programming model for different transaction implementations. This section takes JDBC transactions as an example to introduce Spring transaction management.

Spring support for transactions

A transaction is the unit of work of a set of Atomic operations. In the case of database access, it is a set of SQL instructions. This set of SQL instructions must be executed successfully. If they are not executed successfully for some reason (for example, there is an error in one line of SQL), all previously executed SQL instructions will be undone.

To take a simple example, when a customer transfers money from Bank A to Bank B, the action to be made is to deduct money from Bank A's account and add the amount of the transfer to Bank B. both actions must be successful. If one action fails, the transfer fails.

The transaction must also maintain the consistency of the resources involved (Consistent). For example, in the case of a bank account, the transfer amount of the two accounts and the withdrawal amount of account B cannot be greater than the deposit amount of account A. Each transaction must be Isolated from each other, for example, there may be two transactions in the An account, deposit and withdrawal at the same time, the two transactions basically do not need to be aware of each other's existence. The transaction must also be Durable, and after a transaction, the transaction must be recorded.

Here you will see how JDBC uses transaction management. First, let's take a look at the atomic implementation of the transaction. In JDBC, you can manipulate the setAutoCommit () method of Connection. Given the false parameter, after issuing a series of SQL statements, execute commit () of Connection to send out the changes. If an error occurs, execute rollback () to undo all execution, for example:

Try {

.

Connection.setAutoCommit (false)

.

/ / A series of SQL operations

Connection.commit ()

} catch (SQLException) {

/ / error occurred, undo all changes

Connection.rollback ()

}

The transaction management of JDBC is encapsulated in Spring. The abstract key of Spring transaction management lies in the implementation of org.springframework.transaction.PlatformTransactionManager interface.

Public interface PlatformTransactionManager {

TransactionStatus getTransaction (TransactionDefinition

Definition) throws TransactionException

Void commit (TransactionStatus status)

Throws TransactionException

Void rollback (TransactionStatus status)

Throws TransactionException

}

The PlatformTransactionManager interface has many specific transaction implementation classes, such as DataSourceTransactionManager, HibernateTransactionManager, JdoTransaction- Manager, JtaTransactionManager and so on. By relying on the PlatformTransactionManager interface and various technical implementations, Spring allows developers to use a consistent programming model in transaction management, even if different transaction management technologies are used.

TransactionException is Unchecked Exception. The failure of a transaction is usually a fatal error, and Spring does not force you to handle it, but lets you choose whether or not to catch an exception.

The getTransaction () method passes a TransactionDefinition object back and forth according to a TransactionStatus object. The instance of the TransactionDefinition API defines the isolation degree of the transaction (Isolation level), propagation behavior (Propagation behavior), timeout (Timeout), read-only (Read-only), and so on. TransactionStatus represents a transaction initiated or existing, and you can use it to control the execution or investigation status of the transaction:

Public interface TransactionStatus {

Boolean isNewTransaction ()

Void setRollbackOnly ()

Boolean isRollbackOnly ()

}

Spring provides programmatic transaction management (Programmatic transaction management) and declared transaction management (Declarative transaction management):

Programmatic transaction management

Programmatic transaction management can clearly control the boundaries of transactions, that is, you can achieve fine-grained transaction control by implementing transaction start time, undo time, end time, and so on.

Declarative transaction management

However, in most cases, transactions do not need fine-grained control, but use declarative transaction management, the advantage is that the relevant API of Spring transaction management can not be involved in the program, from the object's point of view, it does not know that it is being brought into transaction management, when transaction management is not needed, as long as you modify the settings on the settings file, you can remove the transaction management service.

JDBC programming transaction management Spring provides two ways to implement programmatic transaction management, one is to use PlatformTransaction- Manager directly, and the other is to use org.springframework.transaction.support.Transaction- Template.

Let's take a look at how to use PlatformTransactionManager. Using its implementation class DataSourceTransactionManager here, you can rewrite the JdbcTemplateDemo project in the previous sections so that it has transaction management functionality. Modify the insert () method of the UserDAO class to demonstrate: ProgrammaticTransactionDemo UserDAO.java

Package onlyfun.caterpillar

Import java.util.Iterator

Import java.util.List

Import java.util.Map

Import javax.sql.DataSource

Import org.springframework.dao.DataAccessException

Import org.springframework.jdbc.core.JdbcTemplate

Import org.springframework.jdbc.

Datasource.DataSourceTransactionManager

Import org.springframework.transaction.TransactionDefinition

Import org.springframework.transaction.TransactionStatus

Import org.springframework.transaction.

Support.DefaultTransactionDefinition

Public class UserDAO implements IUserDAO {

Private DataSourceTransactionManager transactionManager

Private DefaultTransactionDefinition def

Private JdbcTemplate jdbcTemplate

Public void setDataSource (DataSource dataSource) {

JdbcTemplate = new JdbcTemplate (dataSource)

TransactionManager =

New DataSourceTransactionManager (dataSource)

/ / establish the definition of the transaction

Def = new DefaultTransactionDefinition ()

Def.setPropagationBehavior (

TransactionDefinition.PROPAGATION_REQUIRED)

}

Public void insert (User user) {

String name = user.getName ()

Int age = user.getAge () .intValue ()

TransactionStatus status =

TransactionManager.getTransaction (def)

Try {

JdbcTemplate.update ("INSERT INTO user (name,age)"

+ "VALUES ('" + name + "'," + age + ")

/ / there is an error in the following SQL to test the transaction

JdbcTemplate.update ("INSER INTO user (name,age)"

+ "VALUES ('" + name + "'," + age + ")

}

Catch (DataAccessException e) {

TransactionManager.rollback (status)

Throw e

}

TransactionManager.commit (status)

}

Public User find (Integer id) {

List rows = jdbcTemplate.queryForList (

"SELECT * FROM user WHERE id=" + id.intValue ()

Iterator it = rows.iterator ()

If (it.hasNext ()) {

Map userMap = (Map) it.next ()

Integer I = new Integer (

UserMap.get ("id") .toString ()

String name = userMap.get ("name") .toString

Integer age = new Integer (

UserMap.get ("age") .toString ()

User user = new User ()

User.setId (I)

User.setName (name)

User.setAge (age)

Return user

}

Return null

}

}

DataSourceTransactionManager is used for transaction management in the insert () method. If an exception occurs, the Rollback of the transaction occurs in the catch block, and the wrong SQL is deliberately written in the insert () method (note that the INSERT method is missing a T), so the data is not actually stored in the database.

To use the MySQL database for transaction processing, you must establish a table type that supports transactions, such as the table type of InnoDB. Here, the SQL used to create the table is as follows:

CREATE TABLE user (

Id INT (11) NOT NULL auto_increment PRIMARY KEY

Name VARCHAR (100) NOT NULL default''

Age INT

) TYPE = InnoDB

Another way to implement programmatic transaction management is to use TransactionTemplate, which requires an instance of TransactionManager, as follows:

TransactionTemplate transactionTemplate =

New TransactionTemplate (transactionManager)

...

TransactionTemplate.execute (new TransactionCallback () {

Public Object doInTransaction (TransactionStatus status) {

Return jdbcTemplate.update ("INSERT INTO user (name,age)"

+ "VALUES ('" + name + "'," + age + ")

}

});

If an exception occurs, Rollback will occur, otherwise the transaction will be committed, or if there is no return value, you can also use TransactionCallbackWithoutResult:

TransactionTemplate.execute (

New TransactionCallbackWithoutResult () {

Public void doInTransactionWithoutResult (

TransactionStatus status) {

. ...

}

});

5.3.3 JDBC declares transaction management

Spring's declarative transaction management relies on its AOP framework. The advantage of using declarative transaction management is that transaction management cannot invade the components you develop, specifically, DAO objects are not aware that they are in the process of transaction management, and should be, because transaction management is a system-level service, not part of the business logic, and only needs to be reconfigured in the definition file if you want to change the transaction management strategy.

For example, you can modify the JdbcTemplateDemo project in section 5.2.1 to add transaction management services to it without modifying the UserDAO class. A simple way is to use TransactionProxyFactoryBean to specify the transaction management objects and their methods to intervene, which need to be modified in the definition file, as shown below:

DeclarativeTransactionDemo beans-config.xml

Onlyfun.caterpillar.IUserDAO

PROPAGATION_REQUIRED

TransactionProxyFactoryBean needs a TransactionManager. Because JDBC is used here, DataSourceTransactionManager,TransactionProxyFactoryBean is a proxy object. The "target" attribute specifies the object to be proxied, and transaction management automatically intervenes before and after the specified method. Here, "transactionAttributes" attribute is used to specify. "insert*" means that all specified method names starting with insert should be included in transaction management. You can also specify the full name of the method. If an error occurs during method execution, All previous actions are automatically withdrawn, otherwise they are submitted normally.

"PROPAGATION_REQUIRED" is specified on methods such as "insert*", which means that the operation is performed in the current transaction and a new one is created if the transaction does not exist. The relevant constant meaning can be found in the TransactionDefinition interface of the API file. You can add multiple transaction definitions, separated by a comma, for example, you can add read-only, or specify that the operation be withdrawn when an exception occurs:

PROPAGATION_REQUIRED,readOnly,-MyCheckedException

When MyCheckedException is preceded by "-", the operation is undone when the specified exception occurs, and if it is preceded by "+", it is submitted immediately when the exception occurs.

Since "userDAO" is represented by "userDAOProxy", what you need to do is to get "userDAOProxy" instead of "userDAO", for example:

DeclarativeTransactionDemo SpringDAODemo.java

Package onlyfun.caterpillar

Import org.springframework.context.ApplicationContext

Import org.springframework.context.

Support.ClassPathXmlApplicationContext

Public class SpringDAODemo {

Public static void main (String [] args) {

ApplicationContext context =

New ClassPathXmlApplicationContext (

"beans-config.xml")

User user = new User ()

User.setName ("caterpillar")

User.setAge (new Integer (30))

IUserDAO userDAO =

(IUserDAO) context.getBean ("userDAOProxy")

UserDAO.insert (user)

User = userDAO.find (new Integer (1))

System.out.println ("name:" + user.getName ())

}

}

You can also set different TransactionInterceptor to get more administrative details, such as:

Onlyfun.caterpillar.IUserDAO

TransactionInterceptor

Similarly, since the proxy object is no longer set in the settings file, you can simply get an instance of "userDAO" for operation.

At this point, I believe you have a deeper understanding of "how to achieve Spring JDBC transaction management". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue 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