Spring Hibernate Example

0

In this article, I am going to show you an example of spring hibernate integration.

In Hibernate ORM example, I showed you an example of transaction, just using the hibernate provided APIs without the assistance of spring. In this example, we will continue working on it and bring spring into our domain.

1. Hibernate ORM Example

Below is the class from where Hibernate ORM example we manually do it using hibernate provided APIs. There is a lot of boilerplate code that involves around creating configuration, building session factory and opening/closing of sessions. We will now use spring to eliminate the shaded statements and configure SessionFactory in spring’s context file.

HibernateExample:

package com.javarticles.hibernate;
 
import java.io.IOException;
import java.util.List;
 
import org.hibernate.MappingException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
public class HibernateExample {
 
    public static void main(String[] args) throws MappingException, IOException {
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.getTransaction();
        try {
            tx.begin();
            Query query = session.createQuery("from Employee where name='Joe'");
            List empList = query.list();
            System.out.println("Employees found: " + empList.size());
            for(Employee emp: empList) {
                session.delete(emp);
                System.out.println("Deleted " + emp);
            }
            tx.commit();
             
            System.out.println("Create new employee");
            tx = session.getTransaction();
            tx.begin();
            Employee emp = new Employee();
            emp.setName("Joe");
            session.saveOrUpdate(emp);
            tx.commit();
             
            query = session.createQuery("from Employee where name='Joe'");
            System.out.println("List all employees: " + query.list());
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;
 
        } finally {
            session.close();
        }
    }
}

2. Configure LocalSessionFactoryBean to build SessionFactory

We can eliminate SessionFactory creation code by configuring Spring’s LocalSessionFactoryBean which is a factory bean that loads one or more Hibernate mapping XML files to produce a Hibernate SessionFactory.

A SessionFactory depends on:

  1. DataSource bean
  2. The mapping XML files
  3. Hibernate properties or the configuration XML file
<?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"
	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">

	<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="springHibernateExample" class="com.javarticles.spring.hibernate.SpringHibernateExample">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
</beans>

Instead of injecting the hibernate configuration location using configLocation prope, you can directly set the properties using hibernateProperties.

<property name="hibernateProperties">
    <props>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">mnrpass</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">update</property>
    </props>
</property>

hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">mnrpass</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

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;
    }   
}

3. Creation/destruction of SessionFactory and the callbacks

The main interface for interacting with Hibernate is org.hibernate.Session. Once you have the Session object, you can save, update, delete, and load objects from the database.SessionFactory is responsible for opening, closing, and managing Hibernate Sessions.

LocalSessionFactoryBean is a spring provided FactoryBean which builds the SessionFactory during its initialization in afterPropertiesSet(). It is automatically closed in destroy() which calls sessionFactory.close(). The SessionFactory bean is injected into our example so we don’t have to create it ourselves.

Flow of SessionFactory creation:

SessionFactory Creation

SessionFactory Creation

You can override buildSessionFactory or afterSessionFactoryCreation for further processing. One of the other important callback method is postProcessMappings which is called just before the hibernate configuration builds the POJO model using the mapping files. In this callback, you can further add more mapping files.

Flow of SessionFactory destruction:

Closing of SessionFactory

Closing of SessionFactory

 

SpringHibernateExample:

package com.javarticles.spring.hibernate;

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

import org.hibernate.MappingException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringHibernateExample {
    private SessionFactory sessionFactory;
    public static void main(String[] args) throws MappingException, IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        SpringHibernateExample springHibernateExample = (SpringHibernateExample) context.getBean("springHibernateExample");
        springHibernateExample.execute();
    }
    
    public void execute() throws MappingException, IOException {
        Session session = sessionFactory.openSession();
        Transaction tx = session.getTransaction();
        try {
            tx.begin();
            Query query = session.createQuery("from Employee where name='Joe'");
            List empList = query.list();
            System.out.println("Employees found: " + empList.size());
            for(Employee emp: empList) {
                session.delete(emp);
                System.out.println("Deleted " + emp);
            }
            tx.commit();
            
            System.out.println("Create new employee");
            tx = session.getTransaction();
            tx.begin();
            Employee emp = new Employee();
            emp.setName("Joe");
            session.saveOrUpdate(emp);
            tx.commit();
            
            query = session.createQuery("from Employee where name='Joe'");
            System.out.println("List all employees: " + query.list());
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;

        } finally {
            session.close();
        }
    }
    
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}

If already run first, the employees found will return us 1.

Output:

Employees found: 1
Deleted Employee: Joe
Create new employee
List all employees: [Employee: Joe]

Download Source Code

In this article, I have shown you an example of Spring Hibernate Example. You can download the source code here: springhibernateexample.zip

Share.

Comments are closed.