1 Introduction to Spring Framework Transaction Management
Comprehensive transaction support is a compelling reason to use the Spring Framework. The Spring framework provides consistent abstractions for transaction management, with the following benefits:
Consistent programming model across different transaction APIs, such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA) and Java Data Objects ( JDO).
Supports declarative transaction management.
Simpler than complex transaction APIs (e.g., JTA).
Perfectly integrated with Spring’s data access abstraction.
2 Advantages of the Spring Framework’s transaction support model
Traditionally, Java EE developers have two optional transaction management methods: global or local transactions, each with their own limitations.
2.1 Global Transactions
Global transactions allow you to use multiple transaction resources, usually relational databases and message queues. The application manages global transactions via JTA, which is a clunky API. Also, JTA UserTransaction usually needs to come from JNDI, meaning you need to use JNDI. Obviously, using global transactions will limit the reuse of application code, because JTA is usually only available in an application server environment.
In the past, the preferred way to use global transactions was through EJB CMT (Container Managed Transactions): CMT is declarative transaction management. EJB CMT clears the JNDI lookup for related transactions, but EJB itself needs to use JNDI. It eliminates most (but not all) the need to write Java code to control transactions. The important disadvantage is that CMT bundles JTA and application server environments. At the same time, it only works when using EJBs to implement business logic, or at least within a transactional EJB facade.
2.2 Local transactions
Local transactions are specific resources, for example, transactions are associated with JDBC connections. Local transactions are easy to use, but have a significant disadvantage: they cannot span multiple transaction resources. For example, transactions managed using a JDBC connection cannot run within a global JTA transaction. Because the application server is not responsible for transaction management, it does not guarantee correctness across resources. Another disadvantage is the intrusive programming model of local transactions.
2.3 The consistent programming model of the Spring framework
Spring solves the shortcomings of global and local transactions. It allows developers to use a consistent programming model in any environment. Developers only need to write their own code, which abstracts away different transaction management in different environments. The Spring framework provides declarative and programmatic transaction management. Most users prefer declarative transaction management, which is also recommended.
Using programmatic transaction management, developers use Spring framework transaction abstraction and can run on any underlying transaction. Using the preferred declarative model, developers typically write little or no transaction management code and, therefore, do not rely on the Spring Framework transaction API, or other transaction APIs.
3 The key to understanding the Spring framework transaction abstraction
Spring transaction abstraction is the concept of transaction strategy. Transaction strategy is defined through the org.springframework.transaction.PlatformTransactionManager interface:
public interface PlatformTransactionManager {
?TransactionStatus getTransaction(
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? using using using org.springframework.transaction. ? ? ? ? ????‐ ‐ ‐ ‐‐‐‐‐‐‐‐‐‐ void commit(TransactionStatus status) throws TransactionException;
?????? void rollback(TransactionStatus status) throws TransactionException;
}
This is primarily a Service Provider Interface (SPI), although it can use the programming model in your code. Because PlatformTransactionManager is an interface, it is easy to mock and stubbed. It does not require a lookup strategy like JNDI. PlatformTransactionManager is implemented like other objects defined in the Spring IoC container. This benefit makes Spring Framework transactions worth abstracting, even when using JTA. Transaction code is easier to test than using JTA directly.
The TransactionException thrown by the PlatformTransactionManager interface method is an undetected exception (that is, it inherits java.lang.RuntimeException). Transaction failure is fatal. In the rare cases where application code can actually recover from a transaction failure, the application developer can choose to catch and handle TransactionException. The advantage is that developers don't have to force this.
The getTransaction(..) method relies on the TransactionDefinition parameter to return the TransactionStatus object. The returned TransactionStatus can represent a new transaction, or an existing transaction if the matching transaction exists in the current call stack. In fact, this is the latter case. Just like the Java EE transaction context, TransactionStatus is associated with executable transactions.
TransactionDefinition interface description:
Isolation (transaction isolation level): Transaction isolation level. For example, can this transaction read other uncommitted transactions?
Propagation (transaction propagation): Normally, all code executed in transaction scope will run within the transaction. However, you have an option to specify the behavior of transaction method execution when a transaction context already exists. For example, the code can continue to run in an existing transaction (the usual situation); or the existing transaction can be paused and a new transaction created.
Transaction timeout: How long does the transaction run before it expires and is automatically rolled back through the underlying transaction.
Read-only state: Read-only transactions can be used when your code reads but does not modify data. In some cases, read-only transactions are beneficial for optimization, for example, when you use Hibernate.
These settings reflect standard transaction concepts. These underlying concepts are integral to using the Spring Framework or any transaction management solution.
The TransactionStatus interface provides a simple way for transaction code to control executable transactions and query transaction status:
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
void flush();
boolean isCompleted();
Whether you choose declarative or programmatic in Spring For platform transaction management, it is essential to define the correct PlatformTransactionManager implementation. You typically define this implementation via dependency injection. PlatformTransactionManager usually needs to know the working environment: JDBC, JTA, Hibernate, etc. Below is an example of defining a local PlatformTransactionManager. Define JDBC DataSource:If you are using JTA in a Java EE container, then you can get the container's DataSource by using JNDI and Spring's JtaTransactionManager:
?
? ?
JtaTransactionManager does not need to know about the DataSource, or any specific resource, because it uses the container's global transaction management.
You can also use Hibernate’s local transactions. In this case, you need to define Hibernate's LocalSessionFactoryBean, which your application code will use to obtain a Hibernate Session instance.
In this case, the txManager bean is HibernateTransactionManager. Just as the DataSourceTransactionManager needs to reference the DataSource, the HibernateTransactionManager needs to reference the SessionFactory:
????
????
????????
????????????
????????
????
????
????????
????????????hibernate.dialect=${hibernate.dialect}
????????
????
???
?如果你使用Hibernate和Java EE容器管理JTA事務(wù),那么你只用使用JtaTransactionManager:
在所有這些情況下,應(yīng)用程序代碼不需要改變。你僅僅需要改變配置來改變?nèi)绾喂芾硎聞?wù)。
4????使用事務(wù)同步資源
現(xiàn)在應(yīng)該清楚如何創(chuàng)建不同的事務(wù)管理器,和它們?nèi)绾捂溄有枰绞聞?wù)的相關(guān)資源(例如,DataSourceTransactionManager鏈接DataSource,HibernateTransactionManager鏈接SessionFactory等等)。
4.1??? 高級同步方式
首選方式是使用Spring的高級模板基于持久化集成APIs或使用帶有事務(wù)的本地ORM APIs——感知工廠bean或代理管理本地資源工廠。這些事務(wù)感知解決方案內(nèi)部處理資源創(chuàng)建、重用、清理、資源事務(wù)同步選項(xiàng)和異常映射。因此,數(shù)據(jù)訪問代碼沒有處理這些任務(wù),但可以關(guān)注非樣板式持久化邏輯。通常,你使用本地ORM API或通過使用JdbcTemplate獲取模板。
4.2??? 低級同步方式
例如,DataSourceUtils(JDBC)、EntityManagerFactoryUtils(JPA)、SessionFactoryUtils(Hibernate)、PersistenceManagerFactoryUtils(JDO)存在底層同步方式。當(dāng)你想應(yīng)用程序代碼直接處理本地持久化APIs,你使用這些類確保獲取Spring框架管理的實(shí)例,事務(wù)是(可選)同步的,發(fā)生在進(jìn)程中的異常正確映射一致性API。
例如,在JDBC的情況下,傳統(tǒng)的JDBC方式在DataSource上調(diào)用getConnection()方法,你可以使用Spring的org.springframework.jdbc.datasource.DataSourceUtils:
Connection conn = DataSourceUtils.getConnection(dataSource);
如果已存在的事務(wù)已經(jīng)有一個連接同步(鏈接)它,實(shí)例被返回。否則,方法調(diào)用觸發(fā)器創(chuàng)建新的連接,(可選)同步任意已存在的事務(wù),后續(xù)在相同事務(wù)中重用。
這種方式不需要Spring事務(wù)管理(事務(wù)同步是可選的),因此,無論你是否使用Spring管理事務(wù)你都能使用它。
當(dāng)然,一旦你使用Spring的JDBC支持、JPA支持或Hibernate支持,你通常不喜歡使用DataSourceUtils或其它的幫助類。
4.3????TransactionAwareDataSourceProxy
在底層,已經(jīng)存在TransactionAwareDataSourceProxy類。這是目標(biāo)DataSource代理,包裝目標(biāo)DataSource到感知Spring管理事務(wù)。為此,它類似于Java EE服務(wù)器提供的傳統(tǒng)JNDI DataSource。
5????聲明式事務(wù)管理
Spring框架的聲明式事務(wù)管理讓Spring面向切面編程(AOP)成為可能,盡管,Spring框架發(fā)布包以模板形式自帶事務(wù)切面代碼,一般需要理解AOP。
5.1????理解Spring框架的聲明式事務(wù)實(shí)現(xiàn)
通過元數(shù)據(jù)驅(qū)動事務(wù)通知(當(dāng)前基于XML或注解)。AOP聯(lián)合事務(wù)元數(shù)據(jù)產(chǎn)生AOP代理,使用TransactionInterceptor聯(lián)合適當(dāng)?shù)腜latformTransactionManager實(shí)現(xiàn)驅(qū)動事務(wù)環(huán)繞方法調(diào)用。
5.2?Example of declarative transaction implementation
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx ="http://www.springframework.org/schema/tx" ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?schema/beans/spring-beans.xsd ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????/www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring- aop.xsd"> ; & lt;-& gt; & lt; & lt; ;tx:advice id="txAdvice" transaction-manager="txManager"> ?????????????????????????????????????????????????????????????????????????????????????????????????????????????????tx:method name="get*" read-only="true"/> " execution(* x.y.service.FooService .*(..)) "/& gt; & lt; AOP: Advisor Advice-Ref =" TXADVICE "POINTCUT-Ref =" FooserviceOperation "/& GT; & LT;/AOP: Config & LT & LT & LT ;; bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> ????? ????????????????????????????????????????????????????????????????????????????????????????????????????????? ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????,,,,,,,,,, Causes Spring transaction rollback when a runtime exception or Error is thrown. Checked exceptions do not cause Spring transactions to be rolled back. You can explicitly configure the exception type for transaction rollback. ???????????????????????????????????????????????????????-for="NoProductInStockException"/> ??????????????????????????????????????????????????????????????
5.6 Using @Transactional
Enable annotation management:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx=" http://www.springframework.org/schema/tx" beans/spring-beans.xsd ?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring- aop.xsd"> & lt; ---- & gt; ? ? ? @Transactional public class DefaultFooService implements FooService { Foo getFoo(String fooName); Foo getFoo(String fooName, String barName); void insertFoo(Foo foo) ; void updateFoo(Foo foo); } @Transactional settings: class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> ... class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> ... Custom abbreviation annotation @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional("order") public @interface OrderTx { } @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Transactional("account") public @interface AccountTx { } 5.7 Transaction Propagation PROPAGATION_REQUIRED Compared with PROPAGATION_REQUIRED, PROPAGATION_REQUIRES_NEW uses a completely independent transaction. In this case, the underlying physical transaction is different and, therefore, can be committed or rolled back independently, and the rollback status of the outer transaction is not affected by the inner transaction. PROPAGATION_NESTED Use a physics transaction that can roll back to multiple savepoints. This rollback allows the inner transaction scope to trigger a rollback of its scope and the outer transaction to be able to continue the physical transaction even though some operations have been rolled back. This setting is typically mapped to a JDBC savepoint and, therefore, can only be used for JDBC resource transactions. T ProteCted Void DointransactionWithoutResult (TransactionStatus Status) { Try { UpdateOperation1 (); Sexepting ex) { Status.SetrolllLLLLLLLLY (); }}} }); Specify transaction settings: public class SimpleService implements Service { ?private final TransactionTemplate transactionTemplate; ?public SimpleService(PlatformTransactionManager transactionManager) { ??Assert. notNull(transactionManager, "The 'transactionManager' argument must not be null."); this.transactionTemplate = new TransactionTemplate(transactionManager); this.transactionTemplate.setIsolationLevel( TransactionDefinition.ISOLATION_READ_UNCOMMITTED); this .transactionTemplate.setTimeout(30); // 30 Seconds } } Configure TransactionTemplate using Spring XML: class="org.springframework.transaction.support.TransactionTemplate"> 6.2 Using PlatformTransactionManager DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("SomeTxName"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = txManager.getTransaction(def); try { / / Execute business logic } catch (MyException ex) { txManager.rollback(status); throw ex; } txManager.commit(status); 7 Choose programmatic or declarative management of transactions ? If you only have a small number of transaction operations, choose programmatic transaction management. 8 Transaction Binding Events Starting from Spring 4.2, listener events can be bound to transaction phases. @Component public class MyComponent { ???????? @TransactionalEventListener ????? public void handleOrderCreatedEvent(CreationEvent ?????????????????????????????????????????????

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In 2023, AI technology has become a hot topic and has a huge impact on various industries, especially in the programming field. People are increasingly aware of the importance of AI technology, and the Spring community is no exception. With the continuous advancement of GenAI (General Artificial Intelligence) technology, it has become crucial and urgent to simplify the creation of applications with AI functions. Against this background, "SpringAI" emerged, aiming to simplify the process of developing AI functional applications, making it simple and intuitive and avoiding unnecessary complexity. Through "SpringAI", developers can more easily build applications with AI functions, making them easier to use and operate.

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to implement spring programmatic transactions: 1. Use TransactionTemplate; 2. Use TransactionCallback and TransactionCallbackWithoutResult; 3. Use Transactional annotations; 4. Use TransactionTemplate in combination with @Transactional; 5. Customize the transaction manager.

Java implements scheduled tasks In the library that comes with Jdk, there are two ways to implement scheduled tasks, one is Timer, and the other is ScheduledThreadPoolExecutor. When Timer+TimerTask creates a Timer, it creates a thread, which can be used to schedule TimerTask tasks. Timer has four construction methods, and you can specify the name of the Timer thread and whether to set it as a daemon thread. The default name is Timer-number, and the default is not a daemon thread. There are three main methods: cancel(): terminate task scheduling, cancel all currently scheduled tasks, running tasks will not be affected purge(): remove tasks from the task queue

How to set the transaction isolation level in Spring: 1. Use the @Transactional annotation; 2. Set it in the Spring configuration file; 3. Use PlatformTransactionManager; 4. Set it in the Java configuration class. Detailed introduction: 1. Use the @Transactional annotation, add the @Transactional annotation to the class or method that requires transaction management, and set the isolation level in the attribute; 2. In the Spring configuration file, etc.

SpringBoot and SpringCloud are both extensions of Spring Framework that help developers build and deploy microservice applications faster, but they each have different purposes and functions. SpringBoot is a framework for quickly building Java applications, allowing developers to create and deploy Spring-based applications faster. It provides a simple, easy-to-understand way to build stand-alone, executable Spring applications

As a Java developer, learning and using the Spring framework is an essential skill. With the popularity of cloud computing and microservices, learning and using Spring Cloud has become another skill that must be mastered. SpringCloud is a development toolset based on SpringBoot for quickly building distributed systems. It provides developers with a series of components, including service registration and discovery, configuration center, load balancing and circuit breakers, etc., allowing developers to build micro

Detailed explanation of the Bean acquisition method in Spring In the Spring framework, Bean acquisition is a very important part. In applications, we often need to use dependency injection or dynamically obtain instances of beans. This article will introduce in detail how to obtain beans in Spring and give specific code examples. Obtaining the Bean@Component annotation through the @Component annotation is one of the commonly used annotations in the Spring framework. We can do this by adding @Compone on the class
