Best practices for Spring ORM and transaction module in an application
The following are the practices that we have to follow in the design and development of an application:
Avoid using Spring's HibernateTemplate
helper class in the DAO implementation, and use SessionFactory
and EntityManager
in your application. Because of the contextual session capability of Hibernate, use SessionFactory
directly in your DAOs. Additionally, use getCurrentSession()
method to access the transactional current session in order to perform persistence operations in the application. Please refer to the following code:
@Repository public class HibernateAccountRepository implements AccountRepository { SessionFactory sessionFactory; public HibernateAccountRepository(SessionFactory sessionFactory) { super(); this.sessionFactory = sessionFactory; } //... }
In your application, always use the @Repository
annotation for data access objects or repositories...