Question

I have a Service(Hibernate DAOs) which retrieves data from the DB and returns it to the client. One of the developer has inserted the @Transactional on the class itself without any properties set. The bean declaration in the appliciation context of spring specifies that this service is a singleton.

Now the question is, when ever a multiple methods in this service are called, does the spring still keep the session active across multiple method calls? What problems does this bring to me? Is it a good practice? code snippet below.

@Transactional
public class SomeService implements IService{

public TestObjects returnTestObj(){
  return   testDao.findById(11);
}

public TestObjects returnAnotherTestObj(){
   //some processing in the session.
  return testDao.findById(11);
}

}

thanks.

Was it helpful?

Solution

Because of @Transactional (and <tx:annotation-driven> or the corresponding Java configuration) Spring will proxy your SomeService bean. This proxy will possess the transactional behavior, ie. opening a Session, starting a Transaction, committing or rolling back the Transaction, and closing the Session.

when ever a multiple methods in this service are called, does the spring still keep the session active across multiple method calls

The Session will remain open until the method returns. For example

SomeService service = ...// get bean
service.returnTestObj(); // session boundary
service.returnAnotherTestObj(); // other session boundary

What problems does this bring to me? Is it a good practice?

You have to be careful with Hibernate proxies and lazy loading. It is not good or bad practice, it depends on what you want to do. It's relatively customizable through configuration.

OTHER TIPS

Long story short the @Transactional annotation will cause Spring to check if a transaction has been opened prior to method invocation -- and open new / use existing according to the settings -- hence you're code is free from programatically opening and comitting transactions.

Typically the transaction will be closed (comitted) at the end of method body, however if the caller method is also annotated then the transaction might continues.

This part of Spring aspect oriented programming feature. You'd have to spend time reading about it on the manual if you want to know more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top