You are on page 1of 18

Spring ORM Module:

—-----------------
The main intention of the Spring ORM module is to integrate ORM
implementations to the Spring applications.

In general, the following products are implementing ORM.


1. Hibernate
2. Entity Beans
3. JPA
4. Open JPA
5. iBaties
—----
—----
Q)To provide data persistence in enterprise applications we already have the
ORM implemented tools like Hibernate, Entity beans, JPA, Open JPA,.... then
what is the requirement to use Spring ORM?
—---------------------------------------------------------------------------
Ans:
—---
If we want to prepare any application with any ORM implemented tools then we
have to use the following steps.

1. Create Persistence class.


2. Prepare mapping File.
3. Prepare Configuration file
4. Prepare Test Application

To prepare Test Application in Hibernate applications we have to use the


following steps.

1. Create a Configuration object.


2. Create a SessionFactory object.
3. Create a Session object.
4. Create a Transaction object as per the requirement.
5. Perform the persistence operations.
6. Perform either commit or rollback operation as per the requirement.
7. Close Session and Sessionfactory

EX:
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionfactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Employee emp = new Employee();
emp.setEno(111);
emp.setEname(“Durga”);
emp.setEsal(50000.0d);
emp.setEaddr(“Hyd”);
session.save(emp);
tx.commit();
session.close();
sessionFactory.close();

In the above code, Configuration object, Sessionfactory object, Session


object, transaction object, commit or rollback operations are very much
common from one hibernate application to another hibernate application, so
the common code in every application is called Boilerplate code.

Spring-ORM module is able to provide solutions for the developers to reduce


the boilerplate code in every application just by having an abstraction over
all the boilerplate code in the form of the HibernateTemplate class.

IN Spring - ORM , HibernateTemplate classes are able to provide the following


methods directly.

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 cls, Serializable pkVal)
public Object load(Class cls, Serializable pkVal)
—----
—---

If we want to integrate Hibernate applications with Spring ORM Module then we


have to use the following steps.

1. Create a Maven Project with all the Spring and Hibernate dependencies.
2. Create a Bean / POJO class.
3. Create a Hibernate mapping File.
4. Create a DAO interface.
5. Create DAO implementation class
6. Create Spring Configuration File.
7. Create Test application
1. Create a Maven Project with all the Spring and Hibernate dependencies:
—--------------------------------------------------------------------------
To prepare Spring ORM applications we have to use the dependencies.
1. Hibernate3-core
2. MySQL Driver
3. Javassist
4. Spring-orm
5. Spring-Context

2. Create a Bean / POJO class:


public class Employee{
private int eno;
Private String ename;
private float esal;
Private String eaddr;
setXXX() and getXXX()
}

3. Create a Hibernate mapping File:


<!DOCTYPE…..>
<hibernate-mapping>
<class name=”com.dss.beans.Employee” table=”emp1”>
<property name=”eno”/>
<property name=”ename”/>
<property name=”esal”/>
<property name=”eaddr”/>
</class>
</hibernate-mapping>
4. Create a DAO interface:
public interface EmployeeDao{
public String add(Employee emp);
Public Employee search(Employe emp);
public String update(Employee emp)
public String delete(Employee emp)
}
5. Create DAO implementation class:
public class EmployeeDaoImpl implements EmployeeDao{
private HibernateTemplate hibernateTemplate;
@Transactional
public String add(Employee emp){
hibernateTemplate.save(emp);

}
@Transactional
Public Employee search(Employe emp){
Employee emp = (Employee)hibernateTemplate.get(emp);
}
@Transactional
public String update(Employee emp){
hibernateTemplate.update(emp);
}
@Transactional
public String delete(Employee emp){
hibernateTemplate.delete(emp);
}
}

6. Create Spring Configuration File:


—------------------------------------
To prepare Spring Configuration files in Spring - ORM Applications we have to
use the following configuration details.
a. Enable Transaction annotations.
b. DriverManagerDataSource
c. LocalSessionFactoryBean
d. HibenateTransactionManager
e. HibernateTemplate
f. DAO class

Where DriverManagerDataSource configuration is able to provide Spring inbuilt


connection pooling mechanism and it will include the properties like
driverClassName, url, userName and password.

Where LocalSessionFactoryBean configuration is able to create SessionFactory


object by including the below properties
1. dataSource: It will take the dataSource which we configured in the
Spring configuration file.
2. mappingResources: It will take a list of mapping files names.
3. hibernateProperties: It will take all the hibernate properties like
dialect, show sql.... By using <props> tag.

Where the HibenateTransactionManager configuration will activate Transaction


Manager internally to provide transaction support.

Where the HibernateTemplate configuration is able to supply HibernateTemplate


class to perform all the data persistence operations.
Where DAO implementation class configuration will provide DAO objects in the
Spring application in order to perform database operations.

<beans>
<tx:annotation-driven/>
<bean name=”dataSource” class=”....DriverManagerDataSource”>
<property name=”driverClassName” value=”--”/>
<property name=”url” value=”---”/>
<property name=”userName” value=”---”/>
<property name=”password” value=”--”/>
</bean>
<bean name=”sessionFactory” class=”....LocalSessionFactoryBean”>
<property name=”dataSource” ref=”dataSource”/>
<property name=”mappingResources”>
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
<property name=”hibernateProperties”>
<props>
<prop key=”hibernate.dialect”>..MySQLDialect</prop>
<prop key=”hibernate.show_sql”>true</prop>
</props>
</property>

</bean>
<bean name=”transactionManager” class=”...HibernateTransactionManager”>
<property name=”sessionFactory” ref=”sessionFactory”/>
</bean>
<bean name=”hibernateTemplate” class=”....HibernateTemplate”>
<property name=”sessionFactory” ref=”sessionFactory”/>
</bean>
<bean name=”employeeDao” class=”EmployeeDao”>
<property name=”hibernateTemplate” ref=”hibernateTemplate”/>
</bean>
</beans>
EX:
—--
Employee.java
package com.durgasoft.beans;

public class Employee {


private int eno;
private String ename;
private float esal;
private String eaddr;

public int getEno() {


return eno;
}

public void setEno(int eno) {


this.eno = eno;
}

public String getEname() {


return ename;
}

public void setEname(String ename) {


this.ename = ename;
}

public float getEsal() {


return esal;
}

public void setEsal(float esal) {


this.esal = esal;
}

public String getEaddr() {


return eaddr;
}

public void setEaddr(String eaddr) {


this.eaddr = eaddr;
}
}
Employee.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.durgasoft.beans.Employee" table="emp1">
<id name="eno"/>
<property name="ename"/>
<property name="esal"/>
<property name="eaddr"/>
</class>
</hibernate-mapping>

EmployeeService.java
package com.durgasoft.service;

import com.durgasoft.beans.Employee;

public interface EmployeeService {


public String addEmployee(Employee employee);
public Employee searchEmployee(int eno);
public String updateEmployee(Employee employee);
public String deleteEmployee(Employee employee);

EmployeeServiceImpl.java
package com.durgasoft.service;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
@Autowired
private EmployeeDao employeeDao;
@Override
public String addEmployee(Employee employee) {
String status = employeeDao.add(employee);
return status;
}
@Override
public Employee searchEmployee(int eno) {
Employee employee = employeeDao.search(eno);
return employee;
}

@Override
public String updateEmployee(Employee employee) {
String status = employeeDao.update(employee);
return status;
}

@Override
public String deleteEmployee(Employee employee) {
String status = employeeDao.delete(employee);
return status;
}
}

EmployeeDao.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;

public interface EmployeeDao {


public String add(Employee employee);
public Employee search(int eno);
public String update(Employee employee);
public String delete(Employee employee);
}

EmployeeDaoImpl.java
package com.durgasoft.dao;

import com.durgasoft.beans.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class EmployeeDaoImpl implements EmployeeDao{
@Autowired
private HibernateTemplate hibernateTemplate;

@Transactional
@Override
public String add(Employee employee) {
String status = "";
try{
int pkVal = (int) hibernateTemplate.save(employee);
if(pkVal == employee.getEno()){
status = "SUCCESS";
}else{
status = "FAILURE";
}
}catch (Exception exception){
exception.printStackTrace();
}
return status;
}

@Override
public Employee search(int eno) {
Employee employee = hibernateTemplate.get(Employee.class,
eno);
return employee;
}

@Transactional
@Override
public String update(Employee employee) {
String status = "";
try {
hibernateTemplate.update(employee);
status = "SUCCESS";
}catch (Exception exception){
status = "FAILURE";
exception.printStackTrace();
}
return status;
}
@Transactional
@Override
public String delete(Employee employee) {
String status="";
try{
hibernateTemplate.delete(employee);
status = "SUCCESS";
}catch(Exception exception){
status = "FAILURE";
exception.printStackTrace();
}
return status;
}
}

Main.java
package com.durgasoft;

import com.durgasoft.beans.Employee;
import com.durgasoft.dao.EmployeeDao;
import com.durgasoft.service.EmployeeService;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {


public static void main(String[] args) {

EmployeeService employeeService = null;


try {
ApplicationContext applicationContext = new
ClassPathXmlApplicationContext("SpringConfig.xml");
employeeService = (EmployeeService)
applicationContext.getBean("employeeService");
System.out.println("Employee Management System
Application");

System.out.println("--------------------------------------------");
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(System.in));
String status = "";
int eno = 0;
String ename = "";
float esal = 0.0f;
String eaddr = "";
Employee employee = null;
while (true) {
System.out.println();
System.out.println("1. ADD Employee");
System.out.println("2. SEARCH Employee");
System.out.println("3. UPDATE Employee");
System.out.println("4. DELETE Employee");
System.out.println("5. EXIT");
System.out.print("Your Option : ");
int userOption =
Integer.parseInt(bufferedReader.readLine());
switch (userOption){
case 1:
System.out.println("Employee ADD Module");

System.out.println("--------------------------");
System.out.print("Employee Number : ");
eno =
Integer.parseInt(bufferedReader.readLine());
employee =
employeeService.searchEmployee(eno);
if(employee == null) {
System.out.print("Employee Name : ");
ename = bufferedReader.readLine();
System.out.print("Employee Salary :
");
esal =
Float.parseFloat(bufferedReader.readLine());
System.out.print("Employee Address :
");
eaddr = bufferedReader.readLine();
employee = new Employee();
employee.setEno(eno);
employee.setEname(ename);
employee.setEsal(esal);
employee.setEaddr(eaddr);
status =
employeeService.addEmployee(employee);
System.out.println("Status : " +
status);
}else{
System.out.println("Status : Employee
Existed Already");
}
break;
case 2:
System.out.println("Employee SEARCH Module");

System.out.println("----------------------------");
System.out.print("Employee Number : ");
eno =
Integer.parseInt(bufferedReader.readLine());
employee =
employeeService.searchEmployee(eno);
if(employee == null){
System.out.println("Status : Employee
Does Not Exist");
}else{
System.out.println("Employee Details");

System.out.println("------------------------");
System.out.println("Employee Number :
"+employee.getEno());
System.out.println("Employee Name :
"+employee.getEname());
System.out.println("Employee Salary :
"+employee.getEsal());
System.out.println("Employee Address :
"+employee.getEaddr());
}
break;
case 3:
System.out.println("Employee UPDATE Module");

System.out.println("-----------------------------");
System.out.print("Employee Number : ");
eno =
Integer.parseInt(bufferedReader.readLine());
employee =
employeeService.searchEmployee(eno);
if(employee == null){
System.out.println("Status : Employee
Does Not Exist");
}else{
System.out.print("Employee Name : Old :
"+employee.getEname()+" New : ");
ename = bufferedReader.readLine();
String newEname =
ename==null||ename.equals("")? employee.getEname() : ename;

System.out.print("Employee Salary : Old :


"+employee.getEsal()+" New : ");
String sal= bufferedReader.readLine();
float newEsal =
sal==null||sal.equals("")? employee.getEsal() :
Float.parseFloat(sal);

System.out.print("Employee Address: Old :


"+employee.getEaddr()+" New : ");
eaddr = bufferedReader.readLine();
String newEaddr =
eaddr==null||eaddr.equals("")? employee.getEaddr() : eaddr;

Employee employee1 = new Employee();


employee1.setEno(eno);
employee1.setEname(newEname);
employee1.setEsal(newEsal);
employee1.setEaddr(newEaddr);

status =
employeeService.updateEmployee(employee1);
System.out.println("Status :
"+status);
}
break;
case 4:
System.out.println("Employee DELETE Module");

System.out.println("---------------------------");
System.out.print("Employee Number : ");
eno =
Integer.parseInt(bufferedReader.readLine());
employee =
employeeService.searchEmployee(eno);
if(employee == null){
System.out.println("Status : Employee
Does Not Exist");
}else{
status =
employeeService.deleteEmployee(employee);
System.out.println("Status : "+status);
}
break;
case 5:
System.out.println("*******Thank You for Using
Employee Management System Application*******");
System.exit(0);
break;
default:
System.out.println("Wrong Entry, please enter
the number from 1,2,3,4 and 5");
break;
}
}
} catch (Exception exception) {
exception.printStackTrace();
}

}
}

SpringConfig.xml
<?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:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<tx:annotation-driven/>
<context:component-scan base-package="com.durgasoft.*"/>

<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:3300/durgadb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean name="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean name="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager
">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean name="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean name="employeeDao"
class="com.durgasoft.dao.EmployeeDaoImpl"/>

</beans>

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.durgasoft</groupId>
<artifactId>springormapp01</artifactId>
<version>1.0-SNAPSHOT</version>

<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.31</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.30.RELEASE</version>
</dependency>
<!--
https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.30.RELEASE</version>
</dependency>

</dependencies>

</project>

7. Create Test application

You might also like