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 annotations for transaction management in Spring

2025-02-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article introduces how Spring uses annotations for transaction management. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

Steps to use:

Step 1. Introduce namespaces into the spring configuration file

Step 2. Bean with @ Transactional annotations is automatically configured to support declarative transactions

Step 3. At the declaration of the interface or class, write a @ Transactional.

If you write only on the interface, the implementation class of the interface will inherit the specific methods of the implementation class of the interface, which can override the settings at the class declaration

@ Transactional / / Class-level annotations, methods that apply to all public in the class

Propagation behavior and isolation level of transactions

When you use the annotated transaction management of spring, you may be a little at a loss about the propagation behavior and isolation level of the transaction. Here is a detailed introduction for easy reference.

Annotation method of things: @ Transactional

When marked in front of the class, all methods in the marked class are transactional, for example:

@ Transactionalpublic class TestServiceBean implements TestService {}

When some methods in a class do not need things:

@ Transactionalpublic class TestServiceBean implements TestService {private TestDao dao; public void setDao (TestDao dao) {this.dao = dao;} @ Transactional (propagation = Propagation.NOT_SUPPORTED) public List getAll () {return null;}}

Introduction to the behavior of spreading things:

@ Transactional (propagation=Propagation.REQUIRED)

If there is a transaction, join the transaction, and if not, create a new one (by default)

@ Transactional (propagation=Propagation.NOT_SUPPORTED)

The container does not open a transaction for this method

@ Transactional (propagation=Propagation.REQUIRES_NEW)

Regardless of whether there is a transaction or not, create a new transaction, suspend the original, finish the new execution, and continue to execute the old transaction

@ Transactional (propagation=Propagation.MANDATORY)

Must be executed in an existing transaction, otherwise an exception is thrown

@ Transactional (propagation=Propagation.NEVER)

Must be executed in a transaction that does not exist, or an exception is thrown (as opposed to Propagation.MANDATORY)

@ Transactional (propagation=Propagation.SUPPORTS)

If another bean calls this method and declares the transaction in another bean, then use the transaction. If other bean does not declare a transaction, then there is no transaction.

Thing timeout setting:

@ Transactional (timeout=30) / / 30 seconds by default

Transaction isolation level:

@ Transactional (isolation = Isolation.READ_UNCOMMITTED)

Reading uncommitted data (dirty reading, non-repeatable reading) is basically not used

@ Transactional (isolation = Isolation.READ_COMMITTED)

Read submitted data (unrepeatable and phantom readings occur)

@ Transactional (isolation = Isolation.REPEATABLE_READ)

Repeatable (there will be hallucinations)

@ Transactional (isolation = Isolation.SERIALIZABLE)

Serialization

MYSQL: default to REPEATABLE_READ level

SQLSERVER: default is READ_COMMITTED

Dirty read: one transaction reads uncommitted update data from another transaction

Non-repeatable: in the same transaction, the results returned by reading the same data multiple times are different, in other words

Subsequent reads can read updated data that has been committed by another transaction. On the contrary, "readable" is repeated multiple times in the same transaction

When reading data, it is guaranteed that the read data is the same, that is, subsequent reads cannot read the updated data that has been committed by another transaction.

Illusion: one transaction reads insert data committed by another transaction

Description of parameters commonly used in @ Transactional annotations

Parameter name

Function description

ReadOnly

This property is used to set whether the current transaction is read-only, true is read-only, false is read-write, and the default value is false. For example: @ Transactional (readOnly=true)

RollbackFor

This property is used to set the array of exception classes that need to be rolled back, and when an exception in the specified exception array is thrown in the method, the transaction rollback occurs. For example:

Specify a single exception class: @ Transactional (rollbackFor=RuntimeException.class)

Specify multiple exception classes: @ Transactional (rollbackFor= {RuntimeException.class, Exception.class})

Continue the table)

Parameter name

Function description

RollbackForClassName

This property is used to set the array of exception class names that need to be rolled back, and when an exception in the specified exception name array is thrown in the method, the transaction rollback occurs. For example:

Specify a single exception class name: @ Transactional (rollbackForClassName= "RuntimeException")

Specify multiple exception class names: @ Transactional (rollbackForClassName= {"RuntimeException", "Exception"})

NoRollbackFor

This property is used to set an array of exception classes that do not need to be rolled back, and no transaction rollback occurs when an exception in the specified exception array is thrown in the method. For example:

Specify a single exception class: @ Transactional (noRollbackFor=RuntimeException.class)

Specify multiple exception classes: @ Transactional (noRollbackFor= {RuntimeException.class, Exception.class})

NoRollbackForClassName

This property is used to set an array of exception class names that does not need to be rolled back, and no transaction rollback occurs when an exception in the specified exception name array is thrown in the method. For example:

Specify a single exception class name: @ Transactional (noRollbackForClassName= "RuntimeException")

Specify multiple exception class names:

@ Transactional (noRollbackForClassName= {"RuntimeException", "Exception"})

Propagation

This property is used to set the propagation behavior of the transaction, as shown in Table 6-7.

For example: @ Transactional (propagation=Propagation.NOT_SUPPORTED,readOnly=true)

Isolation

This property is used to set the transaction isolation level of the underlying database. The transaction isolation level is used to deal with the concurrency of multiple transactions. The default isolation level of the database is usually used and basically does not need to be set.

Timeout

This property is used to set the number of timeout seconds for a transaction. A default value of-1 means never timeout.

A few points to note:

1 @ Transactional can only be applied to public methods. For other non-public methods, no error will be reported if @ Transactional is marked, but the method has no transaction function.

Using spring transaction manager, spring is responsible for opening, committing and rolling back the database. By default, runtime exceptions (throw new RuntimeException ("comments") are rolled back, that is, exceptions that are not checked (unchecked) are rolled back. However, the exception that needs to be caught (throw new Exception) will not be rolled back, that is, when the exception being checked (that is, an exception thrown at non-runtime, the exception that the compiler will check is called checked exception or checked exception), we need to specify a way for transaction rollback to roll back all exceptions by adding @ Transactional (rollbackFor= {Exception.class, other exceptions}). If you let the unchecked exception not roll back: @ Transactional (notRollbackFor=RunTimeException.class)

It is as follows:

@ Transactional (rollbackFor=Exception.class) / / specify rollback, rollback if an exception Exception is encountered

Public void methodName () {

Throw new Exception ("comments")

}

@ Transactional (noRollbackFor=Exception.class) / / specifies that it will not be rolled back and will be rolled back if it encounters run-time exceptions (throw new RuntimeException ("comment");)

Public ItimDaoImpl getItemDaoImpl () {

Throw new RuntimeException ("comments")

}

3. The @ Transactional annotation should only be applied to public visibility methods. If you use the @ Transactional annotation on a protected, private, or package-visible method, it will not report an error, but this annotated method will not show the configured transaction settings.

4. @ Transactional annotations can be applied to interface definitions and interface methods, class definitions, and class public methods. Note, however, that the mere occurrence of the @ Transactional annotation is not enough to turn on the transaction behavior, it is just a kind of metadata that can be used by the @ Transactional annotation and the beans with transaction behavior that is appropriately configured above. In the above example, it is the presence of the element that starts the transaction behavior.

5. The advice of the Spring team is that you use @ Transactional annotations on specific classes (or methods of classes), rather than on any interfaces that the class wants to implement. Of course you can use the @ Transactional annotation on the interface, but this will only take effect if you set up an interface-based proxy. Because annotations are not inheritable, this means that if you are using a class-based proxy, the transaction settings will not be recognized by the class-based proxy, and the object will not be wrapped by the transaction agent (will be identified as serious). Therefore, take the advice of the Spring team and use the @ Transactional annotation on specific classes.

So much for sharing about how Spring uses annotations for transaction management. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Servers

Wechat

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

12
Report