Nico Huysamen
Nico Huysamen

Reputation: 10417

Spring Transactions with Hibernate and SQL best practice

We are currently using Spring MVC to implement REST web services. We now want to implement some kind of data persistence, and I am looking at what the options are. Spring Transactions + Hibernate + MySQL seem to be a quite popular approach, but every single blog / tutorial I have looked at does it differently.

Can anyone guide me to what could be considered the "best practice" for data persistance using Spring? I would like to make it annotation based, as this seems more natural and maintainable to me.

But now in some places I have read that HibernateTemplate should not be used anymore. And some people use the *Dao interface and *DaoImpl with @Repository approach, while others use *Service with @Service approach.

Thanks in advance for any advice.

Upvotes: 1

Views: 547

Answers (3)

Aravind A
Aravind A

Reputation: 9697

The usage of HibernateTemplate is discouraged in the HibernateTemplate documentation at

http://static.springsource.org/spring/docs/2.0.3/api/org/springframework/orm/hibernate3/HibernateTemplate.html

NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate3 style of coding data access objects instead, based on SessionFactory.getCurrentSession(). (Spring's LocalSessionFactoryBean automatically supports Spring transaction management for the Hibernate3 getCurrentSession() method.)

The usage of @Repository or @Service does not make any difference but I believe that these annotations would have further DAO/Service level support in the future which would make their usage more precise.

I personally prefer the usage if @Repository in the DAO layer to demarcate my service and business layers.

Upvotes: 0

lalit
lalit

Reputation: 1475

Hibernate Template was needed when hibernate did not supported the notion of having one session per thread. Now the better approach is to use getCurrentSession method on SessionFactory directly.

With HibernateTemplate the other issue is that if there are newer api's exposed on SessionFactory then one has to wait for the new release of Hibernate Template to support that.

In a nutshell, use SessionFactory directly

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691635

HibernateTemplate is indeed not very useful, and the Spring doc advises considering not to use it anymore.

@Repository and @Service basically do the same thing, except (AFAIK) two things:

  • @Repository makes it clear that the service is a DAO, and not a business service
  • exceptions thrown from an @Repository annotated service are translated to Spring's persistence exception classes. This means that you won't get Hibernate exceptions, but Spring exceptions wrapping Hibernate ones.

Upvotes: 4

Related Questions