Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination hibernate @Transactional & ehcache @Cacheable always creates DB transaction

While doing loadtesting on our application I noticed that if you use @Transactional and @Cacheable annotions that hibernate always creates a database transaction. Is there an easy way to prevent this? A more eleberate way to solve this within spring is to have following class/interfaces

  • Servicelayer-interface
  • Cacheable annotated class which is just a proxy/forward to
  • Transactional annotation implentation class

What happens is the following

Call 1:

  1. Transaction gets created
  2. class method gets called
  3. result cached & returned

Call 2:

  1. Transaction gets created
  2. Cached result gets returned

The prefered result should be:

Call 1:

  1. Transaction gets created
  2. class method gets called
  3. result cached & returned

Call 2:

  1. Cached result gets returned
like image 659
user1344117 Avatar asked May 21 '12 10:05

user1344117


People also ask

What does @transactional do in hibernate?

The @Transactional annotation is the metadata that specifies the semantics of the transactions on a method. We have two ways to rollback a transaction: declarative and programmatic. In the declarative approach, we annotate the methods with the @Transactional annotation.

Is @transactional mandatory?

@Transactional(MANDATORY) : fails if no transaction was started ; works within the existing transaction otherwise. @Transactional(SUPPORTS) : if a transaction was started, joins it ; otherwise works with no transaction.

What does the @transactional annotation mean?

The @Transactional annotation is metadata that specifies that an interface, class, or method must have transactional semantics; for example, "start a brand new read-only transaction when this method is invoked, suspending any existing transaction".

Can @transactional be used with interface?

You certainly can place the @Transactional annotation on an interface (or an interface method), but this works only as you would expect it to if you are using interface-based proxies.


1 Answers

You need to change relative order of @Transactional and @Cacheable aspects.

It can be configured using order attribute of <tx:annotation-driven> and <cache:annotation-driven>. See 8.2.4.7 Advice ordering for the meaning of order values.

like image 199
axtavt Avatar answered Sep 28 '22 13:09

axtavt