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.
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.