Programming     Travel Logs     Life Is Good     Surfing Online     About Me
Arm yourself with specific knowledge, accountability, and leverage.
-Naval Ravikant
2018-06-16 22:36:47

Copy this link when reproducing:
http://www.casperlee.com/en/y/blog/183

According to its official document (https://docs.spring.io/spring/docs/2.5.x/javadoc-api/org/springframework/orm/hibernate3/HibernateTemplate.html), HibernateTemplate is a helper class that simplifies Hibernate data access code. Let's find out how it simplifies the code and how to let it works.

/Images/20170922/01.jpg

/Images/20170922/02.jpg

/Images/20170922/03.jpg

/Images/20170922/04.jpg

/Images/20170922/05.jpg

/Images/20170922/06.jpg

/Images/20170922/07.jpg

With the help of the class "org.hibernate.SessionFactory", we can access the database and perform the actions like Add, Update, or Delete, for instance:

	public void add(Day aDay) {
		
		Session session = this.sessionFactory.openSession();
		Transaction trans = session.beginTransaction();
		try {
			
			session.persist(aDay);
			trans.commit();
		}
		catch (Exception ex) {
			
			// dealing with the exceptions
			
			trans.rollback();
		}
	}

    public void update(Day aDay) {
		
		Session session = this.sessionFactory.openSession();
		Transaction trans = session.beginTransaction();
		try {
			
			session.update(aDay);
			trans.commit();
		}
		catch (Exception ex) {
			
			// dealing with the exceptions
			
			trans.rollback();
		}
	}

    public void del(Day aDay) {
		
		Session session = this.sessionFactory.openSession();
		Transaction trans = session.beginTransaction();
		try {
			
			session.delete(aDay);
			trans.commit();
		}
		catch (Exception ex) {
			
			// dealing with the exceptions
			
			trans.rollback();
		}
	}

Clearly, this is very frustrating. Each method is very long and contains similar code to deal with transactions and exceptions. With the help of HibernateTemplate, we can make the method a lot shorter, and we only need to write the core code, and HibernateTemplate will take care of transactions and exceptions for us:

	public void add(Day aDay) {
		
		template.save(aDay);
	}

	public void update(Day aDay) {
		
		template.update(aDay);
	}

	public void delete(Day aDay) {
		
		template.delete(aDay);
	}

Now, let's see how to use Hibernate template in my application.

1. Open the configuration file "WebContent\WEB-INF\config\springmvc-config.xml".

    I. Add a definition for HibernateTemplate:

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
      <property name="sessionFactory" ref="hibernateAnnotatedSessionFactory"></property>
    </bean>

    II. Add a definition for HibernateTransactionManager:

<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
      <property name="sessionFactory" ref="hibernateAnnotatedSessionFactory"></property>
    </bean>

   III. In case you forgot, I've defined the hibernateAnnotatedSessionFactory:

<bean id="hibernateAnnotatedSessionFactory"
      class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="annotatedClasses">
        <list>
          <value>com.casperlee.today.domain.Day</value>
          <value>com.casperlee.today.domain.DayEvent</value>
          <value>com.casperlee.today.domain.DayBirth</value>
          <value>com.casperlee.today.domain.DayDeath</value>
          <value>com.casperlee.today.domain.DayFestival</value>
        </list>
      </property>
      <property name="hibernateProperties">
        <props>
          <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
          <!--
          <prop key="hibernate.current_session_context_class">thread</prop> 
           -->
          <prop key="hibernate.show_sql">false</prop>
        </props>
      </property>
    </bean>

    IV. Remove or comment the line of "<prop key="hibernate.current_session_context_class">thread</prop>".

    V. Enable the transaction manager we have just defined:

<tx:annotation-driven transaction-manager="transactionManager" />

    VI. To use the "tx" prefix, we need to include the following lines in the header:

<beans xmlns="http://www.springframework.org/schema/beans"
    ...
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    ...
    xsi:schemaLocation="
        ...
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd     
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd     
        ...>

2. Use the template in the data access class:

@Service
@Transactional
public class DayServiceImpl implements DayService {
	
	@Autowired
	private HibernateTemplate template;

	@Override
	public Day getByKey(String aKey) {

		Session session = template.getSessionFactory().openSession();
		Query<Day> query = session.createQuery("from Day where key = :keyName", Day.class);
		query.setParameter("keyName", aKey);
		return query.uniqueResult();
	}

	@Override
	public void add(Day aDay) {
		
		template.save(aDay);
	}

	@Override
	public void update(Day aDay) {
		
		template.update(aDay);
	}

	@Override
	public void delete(Day aDay) {
		
		template.delete(aDay);
	}
}

3. Done!