Thursday, 21 April 2016

How to use Hibernate DAO in Spring ?


Spring and Hibernate can integrate using Spring’s SessionFactory.
  1. Configure the Hibernate SessionFactory
  2. Extend your DAO Implementation from HibernateDaoSupport
  3. Wire in Transaction Support with AOP

Configuration in Spring XML
<!-- Configure datasource -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName">
     <value>java:comp/env/jdbc/myDB1</value>  
     <value>jdbc/myDB1</value>
  </property>
</bean>

<!-- Configure session factory and inject datasource to it -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource">
      <ref local="dataSource" />
  </property>
  <property name="mappingResources">
      <list>
     <value>abc.hbm.xml</value>
     <value>xyz.hbm.xml</value>
     <value>lol.hbm.xml</value>
    </list>
  </property>
  <property name="hibernateProperties">
      <props>
     <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
         <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
      </props>
  </property>
</bean>

<!-- Create DAO and inject session factory to it -->
<bean id="myDAO" class="com.genius.MyDao">
  <property name="sessionFactory" ref= "sessionFactory" />
</bean>

Using HibernateDaoSupport class of Spring
Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs.
It has handy methods you can call to get a Hibernate Session, or a SessionFactory.
getHibernateTemplate() returns a HibernateTemplate which wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free.

Example
public class MyDao extends HibernateDaoSupport {
  public User getUser(Long id) {
    return (User) getHibernateTemplate().get(User.class, id);
  }
  public void saveUser(User user) {
    getHibernateTemplate().saveOrUpdate(user);
  }
  public void removeUser(Long id) {
    Object user = getHibernateTemplate().load(User.class, id);
    getHibernateTemplate().delete(user);
  }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.