Recent Posts

Thursday, 8 August 2019

Spring ORM

Spring ORM
     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. Spring has provided the complete ORM module in the form of "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.
1. public void persist(Object entity)
2. public Serializable save(Object entity)
3. public void saveOrUpdate(Object entity)
4. public void update(Object entity)
5. public void delete(Object entity)
6. public Object get(Class entityClass, Serializable id)
7. public Object load(Class entityClass, Serializable id)
8. 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]

JPA [Java Persistence API]
☀ JPA is an API, it can be used to perform database operations in enterprise applications with ORM implementation tools.
☀ JPA was provided by J2EE along with EJB3.0 version as a persistence mechanism.
☀ JPA is a specification provided by SUN Microsystems and it is implemented by some third-party vendors like JBOSS, Eclipse Foundations, Apache etc.
☀ JPA is following ORM rules regulations to achieve data persistency in enterprise applications and it is implemented by the following tools.
• Hibernate ---------> JBOSS
• EclipseLink -------> Eclipse Foundation
• Open JPA --------> Apache Software Foundations

Note
     If we want to use JPA in enterprise applications then we must use either of the JPA implementations.
If we want to prepare JPA applications with "Hibernate" JPA provider then we have to use the following steps.
1. Create Java project in Eclipse with JPA library which includes all Hibernate JARs.
2. Create Entity class under src folder.
3. Create mapping File or Use JPA annotations in POJO class.
4. Create JPA configuration File[persistence.xml]
5. Create Test Application.

     To prepare Test application in JPA we have to use the following steps.
1. Create EntityManagerFactory Object.
2. Create EntityManager Object.
3. Create EntityTransaction Object as per the requirement
4. Perform Persistence operation
5. Perform Commit or rollback operations if we use EntityTransaction.

1. Create EntityManagerFactory Object
    javax.persistence.EntityManagerFactory is a Factory class, it able to manage no of EntityManager object. To get EntitymanagerFactory class object we have to use the following method from javax.persistence.Persistence class.
public static EntityManagerFactory createEntityManagerFactory(String persistence_Unit_Name);
E.g.
EntityManagerFactory factory = Persistence.createEntitymanagerFactory("std");

2. Create EntityManager Object
    javax.persistence.EntityManager is an interface, it able to provide predefined Library to perform persistence operations. To get EntityManager object we have to use the following method from EntiotyManagerFactory.
public EntityManager createEntityManager()
E.g.
EntityManager entManager = factory.createEntitymanager();

3. Create EntityTransaction Object as per the requirement
     javax.persistence.EntityTransaction is a class, it able to provide Tranmsaction support in JPA applications inorder to perform persistence operations. To get EntityTramsaction object we have to use the following method from EntityManager.
public EntityTransaction getTransaction()
E.g.
EntityTransaction entTransaction = entManager.getTransaction();
Note: EntityTransaction contains the following methods in order to complete Transaction.
public void commit()
public void rollback()
Note: EntityTranmsaction is required for only non-select operations only, not for select operations.

4. Perform Persistence operation
To perform Persistence operations, we have to use the following methods from EntityManager object.
1. public Object find (Class entity_Class, Serializable pk_Value)
2. public void persist (Object obj)
3. public void remove (Object obj)

Note:
     To perform Updations, first we have to get Entity object from Database table by using find() method then we have to use set New data to Entity Object then perform commit operation.
package com.ashok.spring.jpa.beans;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 
 * @author ashok.mariyala
 *
 */
@Entity
@Table(name = "employee")
public class Employee {
   @Column(name = "emp_name")
   private String empName;
   @Id
   @Column(name = "emp_id")
   private String empId;
   @Column(name = "emp_address")
   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=" + "]";
   }
}
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
   http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
   version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
   <persistence-unit name="employee">
   <provider>org.hibernate.ejb.HibernatePersistence</provider>
   <mapping-file>com.ashok.spring.jpa.beans.Employee</mapping-file>
   <properties>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/employee" />
      <property name="javax.persistence.jdbc.user" value="root" />
      <property name="javax.persistence.jdbc.password" value="ashok" />
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.format_sql" value="true" />
   </properties>
</persistence-unit>
</persistence>
package com.ashok.spring.jpa.test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import com.ashok.spring.jpa.beans.Employee;
/**
 * 
 * @author ashok.mariyala
 *
 */
public class TestJpaApplication {
   public static void main(String[] args) {
      EntityManagerFactory factory = Persistence.createEntityManagerFactory("employee"); 
      EntityManager entManager = factory.createEntityManager();
      Employee emp = new Employee(); 
      emp.setEmpId("0087"); 
      emp.setEmpName("Ashok Kumar"); 
      emp.setEmpAddress("Bhimavaram"); 
      EntityTransaction tx = entManager.getTransaction(); 
      tx.begin();
      entManager.persist(emp); 
      tx.commit(); 
      System.out.println("Employee Inserted Succssfully");
   }
}

Next Tutorial : Spring Transaction Management

Previous Tutorial : Spring JDBC/DAO

1 comment:

  1. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Final Year Project Centers in Chennai.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

    ReplyDelete