Spring HibernateDaoSupport Example

0

In this article, we will see an example of HibernateDaoSupport. In my previous article on HibernateTemplate, we have seen how to use spring managed transaction. We will improve the example by making our DAO extend HibernateDaoSupport. We just need to provide the SessionFactory to HibernateDaoSupport and it will create its own HibernateTemplate which the sub-classes can access using getHibernateTemplate().

Employee DAO

Employee:

package com.javarticles.spring.hibernate;

public class Employee {
    private long id;
    private String name;
    private String contact;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public String toString() {
        return "Employee: " + name + ", id " + getId();
    }   
}

Define the Employee DAO interface.

EmployeeDao:

package com.javarticles.spring.hibernate;

import java.util.List;

public interface EmployeeDao {
    List<?> findEmployees();

    void deleteEmployees(List<?> empList);

    void createEmployee(String Name);

    void saveEmployee(Employee employee);
}

Your employee DAO implementation will extend HibernateDaoSuppot.

package com.javarticles.spring.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

public class EmployeeHibernateDao extends HibernateDaoSupport implements EmployeeDao {
    
    @Transactional(readOnly=true)
    public List<?> findEmployees() {
        List<?> empList = getHibernateTemplate().find("from Employee where name in (?, ?)", "Joe", "Sam");
        System.out.println("Employees found: " + empList.size());
        return empList;
    }
    
    @Transactional(readOnly=false)
    public void deleteEmployees(List<?> empList) {        
        if (!empList.isEmpty()) {
            getHibernateTemplate().deleteAll(empList);
            System.out.println("Employees deleted");
        }
    }
     
    @Transactional(readOnly=false)
    public void createEmployee(final String Name){
        System.out.println("Create new employee " + Name);
        Employee emp = getHibernateTemplate().execute(new HibernateCallback() {

            public Employee doInHibernate(Session session) throws HibernateException {
                Employee emp = new Employee();
                emp.setName(Name);
                session.saveOrUpdate(emp);
                return emp;
            }
        });
        System.out.println("Employee created " + emp);
    }
    
    @Transactional(readOnly=false)
    public void saveEmployee(Employee emp){
        System.out.println("Create new employee " + emp);
        getHibernateTemplate().save(emp);
        System.out.println("Employee created " + emp);        
    }   
}

Define the beans in applicationContext.xml. Note we are setting sessionFactory bean in employeeHibernateDao‘s bean configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
		http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost/test" />
		<property name="username" value="root" />
		<property name="password" value="mnrpass" />
	</bean>
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mappingResources">
			<list>
				<value>employee.hbm.xml</value>
			</list>
		</property>
		<property name="configLocation" value="classpath:hibernate.cfg.xml" />
	</bean>
	<bean id="employeeHibernateDao" class="com.javarticles.spring.hibernate.EmployeeHibernateDao">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
	<tx:annotation-driven/>
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
    <bean id="hibernateDaoExample" class="com.javarticles.spring.hibernate.HibernateDaoExample">
		<property name="employeeDao" ref="employeeHibernateDao" />
	</bean>
</beans>

Now let’s use the EmployeeDao to do some transactions.

HibernateDaoExample:

package com.javarticles.spring.hibernate;

import java.io.IOException;
import java.util.List;

import org.hibernate.MappingException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.annotation.Transactional;

public class HibernateDaoExample {
    private EmployeeDao empDao;

    public static void main(String[] args) throws MappingException, IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        HibernateDaoExample hibernateDao = (HibernateDaoExample) context
                .getBean("hibernateDaoExample");
        hibernateDao.execute();
    }

    @Transactional(readOnly = false)
    public void execute() {
        List<?> empList = empDao.findEmployees();
        empDao.deleteEmployees(empList);
        empDao.createEmployee("Joe");
        Employee empSam = new Employee();
        empSam.setName("Sam");
        empDao.saveEmployee(empSam);
        System.out.println("List of employees: " + empDao.findEmployees());
    }

    public void setEmployeeDao(EmployeeDao empDao) {
        this.empDao = empDao;
    }

}

Output:

Employees found: 2
Employees deleted
Create new employee Joe
Employee created Employee: Joe, id 63
Create new employee Employee: Sam, id 0
Employee created Employee: Sam, id 64
Employees found: 2
List of employees: [Employee: Joe, id 63, Employee: Sam, id 64]

Download source code

This was an example about HibernateDaoSupport. You can download the source code here: springHibernateDaoSupportExample.zip

Share.

Comments are closed.