Spring hibernate template when to use and why?
Solution 1:
All spring templates (hibernate, jdbc, rest, jpa etc.) have the same pros and cons:
Pro: They perform common setup routines for you, let you skip the boilerplate and concentrate on the logic you want.
Con: you are coupling your application tightly to the spring framework. For this reason, Spring recommends that HibernateTemplate
no longer be used.
Specifically, what HibernateTemplate
did for you was to automatically open and close sessions and commit or rollback transactions after your code executed. However, all of this can be achieved in an aspect-oriented way using Spring's Declarative Transaction Management.
Reference:
- Spring Reference: ORM: Hibernate for the current suggested Spring Hibernate usage patterns
- Spring Reference: Classic Spring Usage: HibernateTemplate
Update:
As of Spring 3.1 (and newer versions), HibernateTemplate
has been removed. See Hibernate for the currently suggested usage patterns.
Solution 2:
Let me clarify one thing that Spring's HibernateTemplate will not be supported going forward, that means Hibernate 4+ versions do not support HibernateTemplate. So it is advised to use declarative transaction management as suggested by Sean.
Solution 3:
HibernateTemplate encapsulates a number of things for you to make your life easier.
It's your choice to use it or not. For that matter, you can work with a database without Hibernate. Spring's JDBC stuff is very good. You might find it easier to get your problem done without having to learn Hibernate.