miyukiutada
Photo credit: miyukiutada
del.icio.us Digg DZone Reddit StumbleUpon
1 | 2 | 3 | Next »
Software Development

Annotation-Based Transactions in Spring

Use Spring annotations to vastly simplify transaction management.

In this article, I'm going to show you how to use transaction management annotations in Spring. I'm using Spring 2.5 though these features have been available at least since Spring 2.0.

Spring provides several different approaches to transaction management:

  • Programmatic: You can write your transactions using Java source code directly. Normally you wouldn't do this unless you needed fine-grained control over some particular transaction.
  • Declarative: You can declare transaction definitions in either a centralized way using XML or in a distributed way using annotations:
    • XML-based: You can configure transactions in Spring's centralized application context file. Once again you have options:
      • Proxy-based: In this approach you wrap your service beans with transactional proxies. The proxy and the service bean both implement the same Java interface so the application can't tell them apart. This is a fairly verbose approach with respect to the actual context configuration though there are techniques you can use to streamline the configuration.
      • AOP-based: Here you define AOP aspects to endow your service beans with transactional semantics. Not quite as verbose as the proxy-based approach.
    • Annotation-based: You can use Java 5 annotations to distribute transaction configuration across Java classes.

As the title suggests, this article deals with annotation-based configuration. In my opinion this is the cleanest and most sensible approach: context file configuration is almost nil and the transaction definitions are conveniently located with the service interfaces and/or beans themselves.

Let's start with a basic overview of transactions, and then we'll get to the good stuff.

Social bookmarks: del.icio.us Digg DZone Reddit StumbleUpon
1 | 2 | 3 | Next »

Comments (20)

Nice article!

One thing: You show annotation on interface in your example, but actually, the official recommendation is to put the annotation on the class.

Here is an except from the docs at

http://static.springframework.org/spring/docs/2.0.x/reference/transaction.html

"...The Spring team's recommendation is that you only annotate concrete classes with the @Transactional annotation, as opposed to annotating interfaces. You certainly can place the @Transactional annotation on an interface (or an interface method), but this will only work as you would expect it to if you are using interface-based proxies. The fact that annotations are not inherited means that if you are using class-based proxies then the transaction settings will not be recognised by the class-based proxying infrastructure and the object will not be wrapped in a transactional proxy (which would be decidedly bad). So please do take the Spring team's advice and only annotate concrete classes (and the methods of concrete classes) with the @Transactional annotation...."
By Tech Per on Mar 18, 2008 at 2:38 AM PDT
Great article Willie. The transaction semantics are changing a little in the 2.5.3 branch in a way that you'll have to update your article soon. Please see the release notes under "Transaction Semantics" shaping up on the spring forum: <a href="http://tinyurl.com/2g9mqh">here</a>
By Lucas Kursof on Mar 18, 2008 at 7:06 AM PDT
@Lucas: :-)

@Tech Per: I moved your comment from the autowiring article to this one because I think that it was meant to go here.

Thanks very much for the nice words and especially for pointing out the problem. I'll update the article accordingly and include an explanation as to what the issue is.
By Willie Wheeler on Mar 18, 2008 at 8:15 PM PDT
Excellent post. Really enjoyed reading your article.

I was hoping to explore Spring's transaction management and had the Spring doc opened for last few days. You just made all that so so simple! :)

Thanks a lot for your effort.
By Asif Iqbal on Mar 18, 2008 at 11:48 PM PDT
Awesome article Willie! Very easy to follow. As you mentioned in the article itself, very simple and easy to understand examples.
I'm pretty new to Spring and still learning it. Your article really helped me to easily go through the Transaction management chapter in the Spring book that I'm following :).
Thank you so much for such a nice article.
By Parthiban Periyasamy on Mar 20, 2008 at 4:39 AM PDT
Really appreciate the feedback. Thanks guys.
By Willie Wheeler on Mar 20, 2008 at 7:08 PM PDT
Wonderful article... Thanks for it
By Kalai on Jun 4, 2008 at 2:21 AM PDT
Really excellent. Thanks for you time and dedication, Willie. It's nice to see that Eclipse (and I'm sure other modern IDEs) will actually offer code completion for the various annotation properties that can be set for @Transactional.

Something curious that I noticed, I had my applicationContext.xml set up with this doctype:

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

and when I added your
<beans xmlns="http://www.springframework.org/schema/beans"...
inside that doctype and then tried to deploy I got errors saying that something was wrong with the xmlns declaration. I removed the doctype and it works perfectly. I'm new to Spring so I hope I've done the right thing. (if so, I hope this tip helps someone else).
By Paul Schwarz on Jun 17, 2008 at 7:23 AM PDT
Thanks Paul. I'm guessing the problems you ran into are related to the fact that that DTD is for Spring 1.2. (If you pull up the DTD in question you can see the reference to Spring 1.2 in the source.) Your namespace declaration on the beans element takes care of validation for you, using XML schemas instead of the older DTD approach.
By Willie Wheeler on Jun 17, 2008 at 2:33 PM PDT

Very Nice article. Thanks.

By Pradeep Tiwari on Feb 23, 2009 at 2:54 AM PST

Thanks for good article. I have one question : Does spring creates proxy for the classes which are annotated with @Transactional. ?

Is this has something to do with AOP?

Appreciate your reply

Thanks Umesh

By Umesh Gohil on Apr 21, 2009 at 11:50 PM PDT

Hi Umesh,

Yep, that is exactly how it works: with proxies and AOP. The AOP concept really goes hand-in-hand with the whole dependency injection thing. A lot of times people talk about dependency injection in conjunction with testing, but in my opinion an even more powerful application is being able to add decorations (like transactional behavior) to components and that's exactly what's going on here.

Willie

By Willie Wheeler on Apr 22, 2009 at 7:27 AM PDT

Thanks Willie, Appreciate your reply.

So it is safe to assume that underlying Transaction have defined Aspect, Pointcut for the @Transaction annotation.

Regards UmeshGohil

By Umesh Gohil on Apr 22, 2009 at 8:57 AM PDT

Excellent article Umesh!!

By Murty on Jun 17, 2009 at 8:23 PM PDT

Huge thanks Willie. Do you know how to incorporate pre and post interceptors when using annotations for transactions? I'm trying to figure that out.

By Abe Mishler on Dec 22, 2009 at 11:32 AM PST

I found exception when using code above. It said : org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.NEVER/MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.

Please your best suggestion to resolve this issue.

Regards, Rendi

By rendi on Feb 9, 2010 at 7:24 PM PST

Hi Willie,

I am new to Spring and unable to understand the difference between proxy-based vs AOP-based approach. I would really appreciate if you can explain these 2 with sample example and best practices of using this two.

Thanks in advance.

Best Regards - Roy

By Roy on Mar 12, 2010 at 12:06 AM PST

This is excellent post Willi.

I am new to Spring and unable to understand the difference between proxy-based vs AOP-based approach. I would really appreciate if you can explain these 2 with sample example and best practices of using this two.

Thanks in advance. Khush.

By Khush on Jul 27, 2010 at 11:59 PM PDT

he myth of pandora is ancient, appears in several distinct Greek versions, pandora armbandand has been interpreted in many ways. In all literary versions, Neu Eingetroffen however, Pandora Armbänder the myth is a rosetta stone kind of theodicy, addressing the question pop information, web easy get, sports fashion, news-fashionof why there is evil in the world. In the seventh hot-winter century BC, Hesiod, both in his Theogony (briefly, without naming Pandora outright rosetta stone language, rosetta stone spanish, abercrombie and fitch, Abercrombie Fitch

By pandora schmuck on Aug 30, 2010 at 11:07 PM PDT

Post a comment

Your name:
Your e-mail address (won't be displayed):
Your web site (optional):
example: www.xyz.com
Your comment:
Preview:
By You
Please help us reduce comment spam:
Spring Annotations RefCard
Check out the new DZone Spring Annotations Refcard by Craig Walls!

What's New?

2009-08-30 - Check out my two-part series on DZone: Spring Integration: A Hands-On Tutorial.
2009-03-25 - My new article Getting Started with Spring Batch 2.0 is available on DZone.
Home | Consulting | Tech Articles | Mailing List | Contact | Spring Blog
Copyright © 2008 Wheeler Software, LLC.