Spring ORM

Spring ORM

In this tutorial, we are going to discuss spring ORM in spring framework. Spring provides API to easily integrate Spring with ORM frameworks such as Hibernate, JPA(Java Persistence API), JDO(Java Data Objects), Oracle Toplink, and iBATIS.

In enterprise applications both the data models are having their own approaches to represent data in effective manner, these differences are able to provide Paradigm Mismatches, these mismatches are able to reduce data persistency in enterprise applications. In general, Object Oriented Data Model and Relational data model are having the following mismatches.

  1. Granularity Mismatch
  2. Sub types mismatch
  3. Associations Mismatch
  4. Identity Mismatch

To improve Data persistency in Enterprise applications, we have to resolve the above specified mismatches between Data models. For this, we have to use “ORM” implementations.

To implement ORM in Enterprise applications, we have to use the following ORM implementations.

  1. EJBs-Entity Beans
  2. JPA
  3. Hibernate
  4. IBatis
  5. JDO

If we want to use Hibernate in enterprise applications, then we have to use the following steps.

  1. Persistence Class or Object.
  2. Prepare Mapping File.
  3. Prepare Hibernate Configuration File
  4. Prepare Hibernate Client Application

To prepare Hibernate Client Application we have to use the following steps.

  1. Create Configuration class object
  2. Create SessionFactory object
  3. Create Session Object
  4. Create Transaction object if it is required.
  5. Persistence operations
  6. Close Session Factory and Session objects.

E.g

Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = session_Factory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = new Employee();
emp.setEno("E0087”);
emp.setEname("Ashok Kumar");
emp.setEsal(45000);
emp.setEaddr("Bhimavaram");
session.save(emp);
tx.commit();
System.out.println("Employee Record inserted Successfully");
session.close();
sessionFactory.close();

To remove the above boilerplate code, SPRING Framework has provided ORM Module. In addition, spring has provided the complete ORM module in the “org.springframework.orm” package.

To abstract the above boilerplate code Spring-ORM module has provided a predefined class in the form of “org.springframework.orm.hibernate4.HibernateTemplate” w.r.t Hibernate4 version.

Note

If we use Hibernate3.x version, then we have to use “org.springframework.orm. hibernate3.HibernateTemplate” class.

org.springframework.orm.hibernate4.HibernateTemplate class has provided the following methods in order to perform persistence operations.

public void persist(Object entity)
public Serializable save(Object entity)
public void saveOrUpdate(Object entity)
public void update(Object entity)
public void delete(Object entity)
public Object get(Class entityClass, Serializable id)
public Object load(Class entityClass, Serializable id)
public List loadAll(Class entityClass)

If we want to Integrate Hibernate with Spring then we have to use the following steps.

  1. Create Java Project with both Spring [including ORM] and Hibernate Libraries.
  2. Create Bean/POJO class.
  3. Prepare Hibernate Mapping File
  4. Create DAO interface with persistence methods.
  5. Create DAO implementation class with HibernateTemplate as property.
  6. Prepare Spring Configuration File
  7. Prepare Client Application
package com.ashok.spring.orm.beans;

/**
 * 
 * @author ashok.mariyala
 *
 */
public class Employee {
   private String empName;
   private String empId;
   private String empAddress;

   public String getEmpName() {
      return empName;
   }

   public void setEmpName(String empName) {
      this.empName = empName;
   }

   public String getEmpId() {
      return empId;
   }

   public void setEmpId(String empId) {
      this.empId = empId;
   }

   public String getEmpAddress() {
      return empAddress;
   }

   public void setEmpAddress(String empAddress) {
      this.empAddress = empAddress;
   }

   @Override
   public String toString() {
      return "Employee [empName=" + empName + ", empId=" + empId + ", empAddress=" + empAddress + ", salary=" + "]";
   }
}
package com.ashok.spring.orm.dao;

import com.ashok.spring.orm.beans.Employee;

/**
 * 
 * @author ashok.mariyala
 *
 */
public interface EmployeeDao {
   public String insert(Employee e); 
   public String update(Employee e); 
   public String delete(Employee e);
   public Employee getEmployee(String eno);
}
package com.ashok.spring.orm.dao;

import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.ashok.spring.orm.beans.Employee;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class EmployeeDaoImpl implements EmployeeDao {
   String status = "";
   private HibernateTemplate hibernateTemplate;

   public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
      this.hibernateTemplate = hibernateTemplate;
   }

   @Override
   @Transactional
   public String insert(Employee e) {
      try {
         hibernateTemplate.save(e);
         status = "Insertion Success";
      } catch (Exception ex) {
         ex.printStackTrace();
         status = "Insertion Failure";
      }
      return status;
   }

   @Override
   @Transactional
   public String update(Employee e) {
      try {
         hibernateTemplate.update(e);
         status = "Updation Success";
      } catch (Exception ex) {
         ex.printStackTrace();
         status = "Updation Failure";
      }
      return status;
   }

   @Override
   @Transactional
   public String delete(Employee e) {
      try {
         hibernateTemplate.delete(e);
         status = "Deletion Success";
      } catch (Exception ex) {
         ex.printStackTrace();
         status = "Deletion Failure";
      }
      return status;
   }

   @Override
   @Transactional
   public Employee getEmployee(String eno) {
      Employee emp = null;
      try {
         emp = (Employee) hibernateTemplate.get(Employee.class, eno);
      } catch (Exception ex) {
         ex.printStackTrace();
      }
      return emp;
   }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   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/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">
   
   <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
      <property name="url" value="jdbc:mysql://localhost:3306/employee" />
      <property name="username" value="root" />
      <property name="password" value="ashok" />
   </bean>
   
   <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="mappingResources">
         <list>
            <value>com/ashok/spring/orm/conf/employee.hbm.xml</value>
         </list>
      </property>
      <property name="hibernateProperties">
         <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
         </props>
      </property>
   </bean>
   <tx:annotation-driven />
   <bean id="transactionManager"
      class="org.springframework.orm.hibernate5.HibernateTransactionManager">
      <property name="sessionFactory" ref="sessionFactory" />
   </bean>
   <bean name="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
      <property name="sessionFactory" ref="sessionFactory" />
      <property name="checkWriteOperations" value="false"></property>
   </bean>
   <bean name="empDao" class="com.ashok.spring.orm.dao.EmployeeDaoImpl">
      <property name="hibernateTemplate" ref="hibernateTemplate" />
   </bean>
</beans>
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name="com.ashok.spring.orm.beans.Employee" table="employee">
      <meta attribute="class-description">This class contains the employee detail.</meta>
      <id name="empId" type="string" column="emp_id"></id>
      <property name="empName" column="emp_name" type="string" />
      <property name="empAddress" column="emp_address" type="string" />
   </class>
</hibernate-mapping>
package com.ashok.spring.orm.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ashok.spring.orm.beans.Employee;
import com.ashok.spring.orm.dao.EmployeeDao;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class TestSpringORMApplication {
   public static void main(String[] args) {
      String configFile = "/com/ashok/spring/orm/conf/applicationContext.xml";
      ApplicationContext context = new ClassPathXmlApplicationContext(configFile);
      EmployeeDao empDao = (EmployeeDao) context.getBean("empDao");
      Employee emp = new Employee();
      emp.setEmpId("E0087");
      emp.setEmpName("Ashok Kumar");
      emp.setEmpAddress("Bhimavaram");
      String status = empDao.insert(emp);
      System.out.println(status);
      System.out.println(empDao.getEmployee("E0087"));
   }
}

Output

Insertion Success
Employee [empName=Ashok Kumar, empId=E0087, empAddress=Bhimavaram]
Spring ORM
Scroll to top