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.
- Granularity Mismatch
- Sub types mismatch
- Associations Mismatch
- 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.
- EJBs-Entity Beans
- JPA
- Hibernate
- IBatis
- JDO
If we want to use Hibernate in enterprise applications, then we have to use the following steps.
- Persistence Class or Object.
- Prepare Mapping File.
- Prepare Hibernate Configuration File
- Prepare Hibernate Client Application
To prepare Hibernate Client Application we have to use the following steps.
- Create Configuration class object
- Create SessionFactory object
- Create Session Object
- Create Transaction object if it is required.
- Persistence operations
- 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.
- Create Java Project with both Spring [including ORM] and Hibernate Libraries.
- Create Bean/POJO class.
- Prepare Hibernate Mapping File
- Create DAO interface with persistence methods.
- Create DAO implementation class with HibernateTemplate as property.
- Prepare Spring Configuration File
- 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]