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; it provides exception translation. Please refer to the following code:

    @Repository 
    public class HibernateAccountRepository{//...} 

The service layer must be separate even though business methods in the services only delegate their responsibilities to the corresponding DAO methods.

Always implement transactions at the service layer of the application and not the DAO layer--this is the best place for transactions. Please refer to the following code:

    @Service 
    @Transactional 
    public class AccountServiceImpl implements AccountService {//...} 

Declarative transaction management is more powerful and convenient to configure in the application, and is a highly recommend approach to use in a Spring application. It separates the cross-cutting concerns from business logic.

Always throw runtime exceptions instead of checked exceptions from the service layer.

Be careful of the readOnly flag for the @Transactional annotation. Mark transactions as readOnly=true when service methods only contain queries.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset