Webnovel Test1108 - LightNovelsOnl.com
You're reading novel online at LightNovelsOnl.com. Please use the follow button to get notifications about your favorite novels and its latest chapters so you can come back anytime and won't miss anything.
Further reading:
Configuring Separate Spring DataSource for Tests
A quick, practical tutorial on how to configure a separate data source for testing in a Spring application.
Read more →
Quick Guide on Loading Initial Data with Spring Boot
A quick and practical example of using data.sql and schema.sql files in Spring Boot.
Read more →
Show Hibernate/JPA SQL Statements from Spring Boot
Learn how you can configure logging of the generated SQL statements in your Spring Boot application.
Read more →
2. Configure Transactions
Spring 3.1 introduces the @EnableTransactionManagement annotation that we can use in a @Configuration cla.s.s and enable transactional support:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
@EnableTransactionManagement
public cla.s.s PersistenceJPAConfig{
@Bean
public LocalContainerEnt.i.tyManagerFactoryBean
ent.i.tyManagerFactoryBean(){
//...
}
@Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEnt.i.tyManagerFactory(
ent.i.tyManagerFactoryBean().getObject() );
return transactionManager;
}
}
However, if we're using a Spring Boot project, and have a spring-dat* or spring-tx dependencies on the cla.s.spath, then transaction management will be enabled by default.
3. Configure Transactions with XML
Before 3.1 or if Java is not an option, here is the XML configuration, using annotation-driven and the names.p.a.ce support:
1
2
3
4
4. The @Transactional Annotation
With transactions configured, we can now annotation a bean with @Transactional either at the cla.s.s or method level:
1
2
3
4
5
@Service
@Transactional
public cla.s.s FooService {
//...
}
The annotation supports further configuration as well:
the Propagation Type of the transaction
the Isolation Level of the transaction
a Timeout for the operation wrapped by the transaction
a readOnly flag – a hint for the persistence provider that the transaction should be read only
the Rollback rules for the transaction
Note that – by default, rollback happens for runtime, unchecked exceptions only. The checked exception does not trigger a rollback of the transaction. We can, of course, configure this behavior with the rollbackFor and noRollbackFor annotation parameters.
5. Potential Pitfalls
5.1. Transactions and Proxies
At a high level, Spring creates proxies for all the cla.s.ses annotated with @Transactional – either on the cla.s.s or on any of the methods. The proxy allows the framework to inject transactional logic before and after the running method – mainly for starting and committing the transaction.
What's important to keep in mind is that, if the transactional bean is implementing an interface, by default the proxy will be a Java Dynamic Proxy. This means that only external method calls that come in through the proxy will be intercepted. Any self-invocation calls will not start any transaction, even if the method has the @Transactionalannotation.
Another caveat of using proxies is that only public methods should be annotated with @Transactional. Methods of any other visibilities will simply ignore the annotation silently as these are not proxied.
This article discusses further proxying pitfalls in great detail here.
5.2. Changing the Isolation Level
We can also change the transaction isolation level:
1
@Transactional(isolation = Isolation.SERIALIZABLE)
Note that this has actually been introduced in Spring 4.1; if we run the above example before Spring 4.1, it will result in:
org.springframework.transaction.InvalidIsolationLevelException: Standard JPA does not support custom isolation levels – use a special JpaDialect for your JPA implementation
5.3. Read-Only Transactions
The readOnly flag usually generates confusion, especially when working with JPA; from the Javadoc:
This just serves as a hint for the actual transaction subsystem; it will not necessarily cause failure of write access attempts. A transaction manager which cannot interpret the read-only hint will not throw an exception when asked for a read-only transaction.
The fact is that we can't be sure that an insert or update will not occur when the readOnly flag is set. This behavior is vendor dependent, whereas JPA is vendor agnostic.
It's also important to understand that the readOnly flag is only relevant inside a transaction. If an operation occurs outside of a transactional context, the flag is simply ignored. A simple example of that would call a method annotated with:
1
@Transactional( propagation = Propagation.SUPPORTS,readOnly = true )
from a non-transactional context – a transaction will not be created and the readOnly flag will be ignored.
5.4. Transaction Logging
A helpful method to understand transactional related issues is fine-tuning logging in the transactional packages. The relevant package in Spring is "org.springframework.transaction", which should be configured with a logging level of TRACE.
6. Conclusion
We covered the basic configuration of transactional semantics using both Java and XML, how to use @Transactionaland best practices of a Transactional Strategy.
As always, the code presented in this article is available over on Github.
I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE
An intro SPRING data, JPA and
Transaction Semantics Details with JPA
Get Persistence right with Spring
Download Now
newestoldestmost voted
Guest
Someone
Great post, just one thing on the following …
"By default, @Transactional will set the propagation to REQUIRED, the readOnly flag to false, and the rollback only for checked exceptions."
Correct me if I´m wrong, but rollback management is set to NON-checked exceptions by default.
0
8 years ago
Guest
Gp
No rollback is on any kind of exception
0
7 years ago
Guest
Eugen Paraschiv
Rollback is indeed done by default for unchecked exceptions.
0
7 years ago
Guest
Łukasz Bachman
Nice one here, my friend. I wanted to dig into transaction management for a long time and this is great post to help me get started Thanks!
-1
8 years ago
Guest
Russell
Nice one. Very useful. One important question. How to change default transaction isolation level in JPA/Hibernate environment. The "hibernate.connection.isolation" only works if you use DriverManager which is not a option in most JEE container.
0
7 years ago
Guest
Eugen Paraschiv
Yeah, isolation has always been a bit of a problem with JPA – I've seen solutions that were doing low level hacks in the JDBC Driver but nothing that worked well unfortunately.
0
6 years ago
Guest
s.h.a.gar Upadhyay
I tried the method you suggested on "5. The API layer transaction strategy" and gave my controller 'Propagation.REQUIRES_NEW' and my service and DAO 'propagation = Propagation.MANDATORY'. When I checked if it worked I get an error :
org.springframework.transaction.IllegalTransactionStateException:
No existing transaction found for transaction marked with propagation
'mandatory'
when i try to call a doLogin() method on my controller.
Do I have to do any additional settings to enable this transaction behavior?
0
7 years ago
Guest
Eugen Paraschiv
The most probable reason for this is that your Controller layer isn't transactional – likely because the controllers themselves are not proxied; one option is to use CGLIB proxies so that the cla.s.s is proxied; an alternative is to have the controllers implement an interface.
A final note is that I updated the article and simplified it to only focus on plain transactions – Transactional Strategies is an advanced topic that I will cover in a future article.
Hope this helps,
Cheers,
Eugen.
0
6 years ago
Guest
Suda
Thank you, could you please share some example links of CGLIB.
0
6 years ago
Guest
Eugen Paraschiv
There is more than one way to do this – either via XML or annotations; one way is: @EnableTransactionManagement(proxyTargetCla.s.s = true) – but I would recommend reading the Spring reference – namely the chapter about proxies and the differences between the available mechanisms.
Hope this helps,
Eugen.
0
6 years ago
Guest
Rahul
Getting the exception:
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.ejb.AbstractEnt.i.tyManagerImpl.flush(AbstractEnt.i.tyManagerImpl.java:959) ~[hibernate-ent.i.tymanager-3.6.10.Final.jar:3.6.10.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_21]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_21]
I have used @Transactional at DAO layer but still getting this error.
-2
6 years ago
Guest
Eugen Paraschiv
Hi Rahul,
Sorry for the late reply – if you're seeing problems with the example project on github, please raise an issue over there and I'll take a look at the problem.
Cheers,
Eugen.
0
6 years ago
Load More Comments
Comments are closed on this article!
report this ad
CATEGORIES
SPRING
REST
JAVA
SECURITY
PERSISTENCE
JACKSON
HTTP CLIENT-SIDE
KOTLIN
SERIES
JAVA "BACK TO BASICS" TUTORIAL
JACKSON JSON TUTORIAL
HTTPCLIENT 4 TUTORIAL
REST WITH SPRING TUTORIAL
SPRING PERSISTENCE TUTORIAL
SECURITY WITH SPRING
ABOUT
ABOUT BAELDUNG
THE COURSES
CONSULTING WORK
META BAELDUNG
THE FULL ARCHIVE
WRITE FOR BAELDUNG
EDITORS
OUR PARTNERS
ADVERTISE ON BAELDUNG
TERMS OF SERVICE
PRIVACY POLICY
COMPANY INFO
CONTACT
x
x