Nearby lessons

16 of 35

Spring - ORM Integration (JPA / Hibernate)

📌 What You Will Learn
  • Understand Spring - ORM Integration (JPA / Hibernate)
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - ORM Integration (JPA / Hibernate) step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

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 Paradiagm 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.

  • Granualarity Mismatch
  • Sub types mismatch
  • Associations Mismatch
  • Identity Mismatch

To improve Data persistency in Enterprise applications we have to resolve the above specified mismtahces 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 sateps. 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.

  • 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.
Example01
JCode Cell
1 
2Configuration cfg = new Configuration();
3cfg.configure("hibernate.cfg.xml");
4SessionFactory session_Factory = cfg.buildSessionFactory();
5Session session = session_Factory.openSession();
6Transaction tx = session.beginTransaction();
7Employee emp = new Employee();
8emp.setEno(111);
9emp.setEname("AAA");
10emp.setEsal(5000);
11emp.setEaddr("Hyd");
12session.save(emp);
13tx.commit();
14System.out.println("Employee Record inserted Succesfully");
15session.close();
16session_Factory.close();
17

Spring ORM

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 fomr 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 inorder 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

  • Create Java Project with both Spring[including ORM] and Hibernate Libraries.

Prepare JAVA project in Eclipse IDE and add the following JAR files to Buildpath in the form of the following Libraries.

Spring4_Lib

spring-aop-4.0.4.RELEASE.jar spring-beans-4.0.4.RELEASE.jar spring-context-4.0.4.RELEASE.jar spring-context-support-4.0.4.RELEASE.jar spring-core-4.0.4.RELEASE.jar spring-expression-4.0.4.RELEASE.jar spring-jdbc-4.0.4.RELEASE.jar commons-io-2.6.jar commons-logging-1.2.jar spring-tx-4.0.4.RELEASE.jar spring-aspects-4.0.4.RELEASE.jar spring-orm-4.0.4.RELEASE.jar

Hibernate4_Lib

ojdbc6.jar antlr-2.7.7.jar dom4j-1.6.1.jar hibernate-commons-annotations-4.0.5.Final.jar hibernate-core-4.3.11.Final.jar hibernate-jpa-2.1-api-1.0.0.Final.jar jandex-1.1.0.Final.jar javassist-3.18.1-GA.jar jboss-logging-3.1.3.GA.jar jboss-logging-annotations-1.2.0.Beta1.jar jboss-transaction-api_1.2_spec-1.0.0.Final.jar hibernate-entitymanager-4.3.11.Final.jar

  • Create Bean/POJO class.
  • public class Student{
  • private String sid;
  • private String sname;
  • private String saddr;
  • setXXX() and getXXX()

Prepare Hibernate Mapping File — Student.hbm.xml

Example05
JCode Cell
1 
2<!DOCTYPE ---- >
3<hibernate-mapping>
4<class name="com.durgasoft.pojo.Student" table="student">
5 <id name="sid" column="SID"/>
6 <property name="sname" column="SNAME"/>
7 <property name="saddr" column="SADDR"/>
8</class>
9</hibernate-mapping>
10

Prepare Hibernate Mapping File

  • Create DAO interface with persistence methods.

The main intention of DAO interface is to declare all Services.

Example06
JCode Cell
1 
2public interface StudentDao {
3public String insert(Student std);
4public String update(Student std);
5public String delete(Student std);
6public Employee getStudent(int eno);
7}
8

Prepare Hibernate Mapping File

  • Create DAO implementation class with HibernateTemplate as property.

The main intention of DAO implementation class is to implement all DAO methods. In DAO implementation class every DAO method must be declared with @Transactional annotation inorder to activate Spring Transaction Service. Note: If we use @Transactional annotation then it is not required to create Transaction object explicitly and iit is not required to perform commit and rollback operations explicitly.

In DAO implementation class we must declare HibernateTemplate property and its respective setXXX() method inorder to inject HibernateTemplate object.

Example07
JCode Cell
1 
2public class StudentDaoImpl implements StudentDao {
3String status = "";
4private HibernateTemplate hibernateTemplate;
5public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
6 this.hibernateTemplate = hibernateTemplate;
7}
8 
9@Transactional
10public String insert(Student std) {
11try {
12 hibernateTemplate.save(std);
13 status = "Insertion Success";
14}catch(Exception ex) {
15 ex.printStackTrace();
16 status = "Insertion Failure";
17}
18return status;
19}
20 
21@Transactional
22public String update(Student std) {
23try {
24 hibernateTemplate.update(std);
25 status = "Updations Success";
26}catch(Exception ex) {
27 ex.printStackTrace();
28 status = "Updations Failure";
29}
30return status;
31}
32 
33@Transactional
34public String delete(Student std) {
35try {
36 hibernateTemplate.delete(std);
37 status = "Deletion Success";
38}catch(Exception ex) {
39 ex.printStackTrace();
40 status = "Deletion Failure";
41}
42return status;
43 
44}
45 
46@Transactional
47public Employee getStudent(int sid) {
48Student std = null;
49try {
50 std = (Student)hibernateTemplate.get(Student.class, sid);
51}catch(Exception ex) {
52 ex.printStackTrace();
53}
54return std;
55}
56}
57

Prepare Spring Configuration File — applicationContext.xml

In Spring Configuration File we must configure the following beans

  • DriverManagerDataSource
  • LocalSessionFactoryBean
  • HibernateTransactionManager
  • HibernateTemplate
  • StudentDaoImpl

 Where org.springframework.jdbc.datasource.DriverManagerDataSource configuration is able to provide Spring inbuilt Connectionpooling Mechanism and it will include the properties liike "driverClassName, url, username, password".

 Where org.springframework.orm.hibernate4.LocalSessionFactoryBean configuration is able to create SessionFactory object by including the properties like

  • dataSource : represents DataSource bean which was configured in Spring Configuration file.
  • mappingResources: It will take list of values contains mapping files in the form of "<list>" tag.
  • hibernateProperties: It will take hibernate properties in the form of "<props>" tag, it must includes mainly "hibernate.dialect" property.

 Where org.springframework.orm.hibernate4.HibernateTransactionManager configuration will activate Transaction Manager inorder to provide Transaction Support and it will include "sessionFactory" property.

 Where org.springframework.orm.hibernate4.HibernateTemplate configuration will provide HibernateTemplate object inorder to perform persistence operations and it will include "sessionFactory" and "checkWriteOperations" with false value.

 Where com.durgasoft.dao.StudentDaoImpl configuration will provide DAO object inorder to access Dao methods and it will include "hibernateTemplate" property.

Note: To use @Transactional annotation in DAO methods , we must use " <tx:annotation- driven/>" tag in spring configuration file.

Example:

Example08
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xmlns:tx="http://www.springframework.org/schema/tx"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/tx
11http://www.springframework.org/schema/tx/spring-tx.xsd
12http://www.springframework.org/schema/aop
13http://www.springframework.org/schema/aop/spring-aop.xsd">
14 
15<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
16<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
17<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
18<property name="username" value="system"/>
19<property name="password" value="durga"/>
20</bean>
21<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
22<property name="dataSource" ref="dataSource"/>
23<property name="mappingResources">
24<list>
25<value>Student.hbm.xml</value>
26</list>
27</property>
28<property name="hibernateProperties">
29<props>
30 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
31 <prop key="hibernate.show_sql">true</prop>
32</props>
33</property>
34</bean>
35<tx:annotation-driven/>
36<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
37<property name="sessionFactory" ref="sessionFactory"/>
38</bean>
39 
40<bean name="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
41<property name="sessionFactory" ref="sessionFactory"/>
42<property name="checkWriteOperations" value="false"></property>
43</bean>
44<bean name="stdDao" class="com.durgasoft.dao.StudentDaoImpl">
45<property name="hibernateTemplate" ref="hibernateTemplate"/>
46</bean>
47</beans>
48

Prepare Client Application

The main intention of Client Application is to get Dao object and to access Dao object.

Example09
JCode Cell
1 
2ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
3StudentDao stdDao = (StudentDao)context.getBean("stdDao");
4Student std = new Student();
5std.setSid("S-111");
6std.setSname("AAA");
7std.setSaddr("Hyd");
8String status = stdDao.insert(std);
9System.out.println(status);
10or
11Student std = (Student)stdDao.getStudent(Student.class,"S-111");
12System.out.println("Student Details");
13System.out.println("--------------------");
14System.out.println("Student Id :"+std.getSid());
15System.out.println("Student Name :"+std.getSname());
16System.out.println("Student Address :"+std.getSaddr());
17or
18Student std = new Student();
19std.setSid("S-111");
20std.setSname("BBB");
21std.setSaddr("Hyd");
22String status = stdDao.update(std);
23System.out.println(status);
24or
25String status = stdDao.delete("S-111");
26System.out.println(status);
27

Application on Spring-Hibernate integration — Employee.java

Example10
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Employee {
5private int eno;
6private String ename;
7private float esal;
8private String eaddr;
9 
10public int getEno() {
11return eno;
12}
13public void setEno(int eno) {
14this.eno = eno;
15}
16public String getEname() {
17return ename;
18}
19public void setEname(String ename) {
20this.ename = ename;
21}
22public float getEsal() {
23return esal;
24}
25public void setEsal(float esal) {
26this.esal = esal;
27}
28public String getEaddr() {
29return eaddr;
30}
31public void setEaddr(String eaddr) {
32this.eaddr = eaddr;
33}
34 
35public String toString() {
36return "["+eno+","+ename+","+esal+","+eaddr+"]";
37}
38 
39}
40

Application on Spring-Hibernate integration — EmployeeDao.java

Example11
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.pojo.Employee;
5 
6public interface EmployeeDao {
7public String insert(Employee e);
8public String update(Employee e);
9public String delete(Employee e);
10public Employee getEmployee(int eno);
11}
12

Application on Spring-Hibernate integration — EmployeeDaoImpl.java

Example12
JCode Cell
1 
2package com.durgasoft.dao;
3import org.hibernate.FlushMode;
4import org.hibernate.Transaction;
5import org.springframework.orm.hibernate4.HibernateTemplate;
6import org.springframework.transaction.annotation.Transactional;
7 
8import com.durgasoft.pojo.Employee;
9 
10public class EmployeeDaoImpl implements EmployeeDao {
11String status = "";
12private HibernateTemplate hibernateTemplate;
13public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
14this.hibernateTemplate = hibernateTemplate;
15 
16}
17 
18@Override
19@Transactional
20public String insert(Employee e) {
21try {
22 hibernateTemplate.save(e);
23 status = "Insertion Success";
24}catch(Exception ex) {
25 ex.printStackTrace();
26 status = "Insertion Failure";
27}
28return status;
29}
30 
31@Override
32@Transactional
33public String update(Employee e) {
34try {
35 hibernateTemplate.update(e);
36 status = "Updations Success";
37}catch(Exception ex) {
38 ex.printStackTrace();
39 status = "Updations Failure";
40}
41return status;
42}
43 
44@Override
45@Transactional
46public String delete(Employee e) {
47try {
48 hibernateTemplate.delete(e);
49 status = "Deletion Success";
50}catch(Exception ex) {
51 ex.printStackTrace();
52 status = "Deletion Failure";
53}
54return status;
55 
56}
57 
58@Override
59@Transactional
60public Employee getEmployee(int eno) {
61Employee emp = null;
62try {
63 emp = (Employee)hibernateTemplate.get(Employee.class, eno);
64}catch(Exception ex) {
65 ex.printStackTrace();
66}
67return emp;
68}
69}
70

Application on Spring-Hibernate integration — Employee.hbm.xml

Example13
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.pojo.Employee" table="emp1">
8 <id name="eno" column="ENO"/>
9 <property name="ename" column="ENAME"/>
10 <property name="esal" column="ESAL"/>
11<property name="eaddr" column="EADDR"/>
12</class>
13</hibernate-mapping>
14

Application on Spring-Hibernate integration — applicationContext.xml

Example14
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:aop="http://www.springframework.org/schema/aop"
6xmlns:tx="http://www.springframework.org/schema/tx"
7xsi:schemaLocation="
8 http://www.springframework.org/schema/beans
9 http://www.springframework.org/schema/beans/spring-beans.xsd
10 http://www.springframework.org/schema/tx
11http://www.springframework.org/schema/tx/spring-tx.xsd
12http://www.springframework.org/schema/aop
13http://www.springframework.org/schema/aop/spring-aop.xsd">
14 
15 
16<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
17<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
18<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
19<property name="username" value="system"/>
20<property name="password" value="durga"/>
21</bean>
22<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
23<property name="dataSource" ref="dataSource"/>
24<property name="mappingResources">
25<list>
26<value>Employee.hbm.xml</value>
27</list>
28</property>
29<property name="hibernateProperties">
30<props>
31 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
32 <!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
33 <prop key="hibernate.show_sql">true</prop>
34</props>
35</property>
36</bean>
37<tx:annotation-driven/>
38<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
39<property name="sessionFactory" ref="sessionFactory"/>
40</bean>
41 
42<bean name="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
43<property name="sessionFactory" ref="sessionFactory"/>
44<property name="checkWriteOperations" value="false"></property>
45</bean>
46<bean name="empDao" class="com.durgasoft.dao.EmployeeDaoImpl">
47<property name="hibernateTemplate" ref="hibernateTemplate"/>
48</bean>
49</beans>
50

Application on Spring-Hibernate integration — Test.java

Example15
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.springframework.context.ApplicationContext;
5import org.springframework.context.support.ClassPathXmlApplicationContext;
6import org.springframework.orm.hibernate4.HibernateTemplate;
7 
8import com.durgasoft.dao.EmployeeDao;
9import com.durgasoft.pojo.Employee;
10 
11public class Test {
12 
13public static void main(String[] args)throws Exception {
14ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
15EmployeeDao empDao = (EmployeeDao)context.getBean("empDao");
16Employee emp = new Employee();
17emp.setEno(111);
18emp.setEname("AAA");
19emp.setEsal(5000);
20emp.setEaddr("Hyd");
21String status = empDao.insert(emp);
22System.out.println(status);
23System.out.println(empDao.getEmployee(111));
24 
25 
26}
27 
28}
29

Application on Spring-Hibernate integration

JPA[Java Persistence API]

Introduction — Student.java

 JPA is a 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......

 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.

  • Create Java project in Eclipse with JPA library which includes all Hibernate JARs.
  • Create Entity class under src folder.
  • Create mapping File or Use JPA annotations in POJO class.
  • Create JPA configuration File[persistence.xml]
  • Create Test Application.
  • Create Java project in Eclipse with JPA library which includes all Hibernate JARs.

This step is same as Java project creation and it will include JPA provider Library that is Hibernate jars.

  • Create Entity class under src folder.
Example17
JCode Cell
1 
2package com.durgasoft.entity;
3public class Student{
4private String sid;
5private String sname;
6private String saddr;
7setXXX() and getXXX()
8}
9

Introduction — Student.xml

  • Create mapping File or Use JPA annotations in POJO class.

It is same as Hibernate mapping file, it will provide mapping between Object Oriented Data model elements like class, Id property, normal properties with the relational data model elements like Table name, Primary Key Columns, normal columns,....

EX:

Example18
JCode Cell
1 
2<hibernate-mapping>
3<class name="com.durgasoft.entity.Student" table="student">
4<id name="sid" column="SID"/>
5<property name="sname" column="SNAME"/>
6<property name="saddr" column="SADDR"/>
7</class>
8</hibernate-mapping>
9

Create JPA configuration File[persistence.xml]

JPA configuration File is same as Hibernate COnfiguration File, it include all JPA configuration details which are required to interact with database .

IN general, we will provide the following configuration details in JPA configuration file.

  • Jdbc Parameters like Driver class name, Driver URL, Database user name, Database password.
  • Dialect configurations
  • Mapping File or Annotated classes configuration
  • Cache Mechanisms configurations
  • Transactions configurations

The default name of the JPA configuration file is "persistence.xml".

Ex persistence.xml

  • <persistence>
  • <persistence-unit name="std">
  • <!-- <class>com.durgasoft.entity.Student</class>-->
  • <mapping-file>Student.xml</mapping-file>
  • <properties>
  • <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
  • <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521

:xe"/>

  • <property name="javax.persistence.jdbc.user" value="system"/>
  • <property name="javax.persistence.jdbc.password" value="durga"/>
  • <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
  • <property name="hibernate.show_sql" value="true"/>
  • <property name="hibernate.format_sql" value="true"/>
  • </properties>
  • </persistence-unit>
  • </persistence>

 Where <persistence> tag is root tag in JPA configuration File.  Where <mapping-file> tag is able to take mapping file configuration  where <propertis> tag will include JPA properties.  Where <property> tag will take a single JPA property like driver class name, driver url,....

Create Test Application

The main intention of Test /Client application is to perform persistence operations .

To prepare Test application in JPA we have to use the following steps.

  • Create EntityManagerFactory Object.
  • Create EntityManager Object.
  • Create EntityTransaction Object as per the requirement
  • Perform Persistence operation
  • Perform Commit or rollback operations if we use EntityTransaction.

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

EX: EntityManagerFactory factory = Persistence.createEntitymanagerFactory("std");

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()

EX: EntityManager entManager = factory.createEntitymanager();

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()

EX: EntityTransaction entTransaction = entManager.getTransaction();

Note: EntityTransaction contains the following methods inorder to complete Transaction.

public void commit() public void rollback()

Note: EntityTranmsaction is required for only non select operations only, not for select operations.

Perform Persistence operation

To perform Persistence operations we have to use the following methods from EntityManager object.

  • public Object find(Class entity_Class, Serializable pk_Value)
  • public void persist(Object obj)
  • 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.

Example25
JCode Cell
1 
2EntityTransaction entTranction = entManager.getTransaction();
3entTransaction.begin();
4Student std = (Student)entManager.find(Student.class, "S-111");
5std.setSname("BBB'");
6std.setSaddr("Sec");
7entTransaction.commit();
8System.out.println("Student Updated Successfully");
9

Perform Persistence operation — Test.java

EX:

Example26
JCode Cell
1 
2public class Test {
3 
4public static void main(String[] args)throws Exception {
5 EntityManagerFactory factory = Persistence.createEntityManagerFactory("std");
6 EntityManager entManager = factory.createEntityManager();
7 Student std = new Student();
8 std.setSid("S-111");
9 std.setSname("AAA");
10 std.setSaddr("Hyd");
11EntityTransaction tx = entManager.getTransaction();
12tx.begin();
13entManager.persist(std);
14tx.commit();
15System.out.println("Student Inserted Succssfully");
16}
17}
18

Simple JPA Example with XML Mapping File — Employee.java

Example27
JCode Cell
1 
2package com.durgasoft.pojo;
3public class Employee {
4private int eno;
5private String ename;
6private float esal;
7private String eaddr;
8public int getEno() {
9 return eno;
10}
11public void setEno(int eno) {
12this.eno = eno;
13}
14public String getEname() {
15return ename;
16}
17public void setEname(String ename) {
18this.ename = ename;
19}
20public float getEsal() {
21return esal;
22}
23public void setEsal(float esal) {
24this.esal = esal;
25}
26public String getEaddr() {
27return eaddr;
28}
29public void setEaddr(String eaddr) {
30this.eaddr = eaddr;
31}
32}
33

Simple JPA Example with XML Mapping File — Employee.xml

Example28
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.pojo.Employee" table="emp1">
8<id name="eno" column="ENO"/>
9<property name="ename" column="ENAME"/>
10<property name="esal" column="ESAL"/>
11<property name="eaddr" column="EADDR"/>
12</class>
13</hibernate-mapping>
14

src/META-INF/persistence.xml — Test.java

  • <?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/p

ersistence/persistence_2_0.xsd"

  • version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
  • <persistence-unit name="emp">
  • <!-- <class>com.durgasoft.pojo.Employee</class>-->
  • <mapping-file>Employee.xml</mapping-file>
  • <properties>
  • <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
  • <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521

:xe"/>

  • <property name="javax.persistence.jdbc.user" value="system"/>
  • <property name="javax.persistence.jdbc.password" value="durga"/>
  • <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
  • <property name="hibernate.show_sql" value="true"/>
  • <property name="hibernate.format_sql" value="true"/>
  • </properties>
  • </persistence-unit>
  • </persistence>
Example29
JCode Cell
1 
2package com.durgasoft.test;
3 
4import javax.persistence.EntityManager;
5import javax.persistence.EntityManagerFactory;
6import javax.persistence.EntityTransaction;
7import javax.persistence.Persistence;
8 
9import com.durgasoft.pojo.Employee;
10 
11public class Test {
12 
13public static void main(String[] args)throws Exception {
14EntityManagerFactory factory = Persistence.createEntityManagerFactory("emp");
15EntityManager entManager = factory.createEntityManager();
16Employee emp = new Employee();
17emp.setEno(111);
18emp.setEname("AAA");
19emp.setEsal(5000);
20emp.setEaddr("Hyd");
21EntityTransaction tx = entManager.getTransaction();
22tx.begin();
23entManager.persist(emp);
24tx.commit();
25System.out.println("Employee Inserted Succssfully");
26}
27}
28

Simple JPA Example with Annotations

If we want to use Annotations in JPA application then we have to use the following steps.

Use javax.persistence provided annotations in Entity class

  • @Entity
  • @Table
  • @Id
  • @Column

Configure Annotated class in persistence.xml file — Employee.java

  • <persistence>
  • <persistence-unit name="std">
  • <class>com.durgasoft.entity.Student</class>
  • </persistence-unit>
  • </persistence>

Example:

Example32
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="emp2")
11public class Employee {
12@Id
13@Column(name="ENO")
14private int eno;
15@Column(name="ENAME")
16private String ename;
17@Column(name="ESAL")
18private float esal;
19@Column(name="EADDR")
20private String eaddr;
21public int getEno() {
22return eno;
23}
24public void setEno(int eno) {
25this.eno = eno;
26}
27public String getEname() {
28return ename;
29}
30public void setEname(String ename) {
31this.ename = ename;
32}
33public float getEsal() {
34return esal;
35}
36public void setEsal(float esal) {
37this.esal = esal;
38}
39public String getEaddr() {
40return eaddr;
41}
42public void setEaddr(String eaddr) {
43this.eaddr = eaddr;
44}
45 
46 
47}
48

src/META-INF/persistence.xml — Test.java

  • <?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/p

ersistence/persistence_2_0.xsd"

  • version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
  • <persistence-unit name="emp">
  • <class>com.durgasoft.pojo.Employee</class>
  • <!-- <mapping-file>Employee.xml</mapping-file> -->
  • <properties>
  • <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
  • <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521

:xe"/>

  • <property name="javax.persistence.jdbc.user" value="system"/>
  • <property name="javax.persistence.jdbc.password" value="durga"/>
  • <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
  • <property name="hibernate.show_sql" value="true"/>
  • <property name="hibernate.format_sql" value="true"/>
  • </properties>
  • </persistence-unit>
  • </persistence>
Example33
JCode Cell
1 
2package com.durgasoft.test;
3 
4import javax.persistence.EntityManager;
5import javax.persistence.EntityManagerFactory;
6import javax.persistence.EntityTransaction;
7import javax.persistence.Persistence;
8 
9import com.durgasoft.pojo.Employee;
10 
11public class Test {
12 
13public static void main(String[] args)throws Exception {
14EntityManagerFactory factory = Persistence.createEntityManagerFactory("emp");
15EntityManager entManager = factory.createEntityManager();
16Employee emp = new Employee();
17emp.setEno(111);
18emp.setEname("AAA");
19emp.setEsal(5000);
20emp.setEaddr("Hyd");
21EntityTransaction tx = entManager.getTransaction();
22tx.begin();
23entManager.persist(emp);
24tx.commit();
25System.out.println("Employee Inserted Succssfully");
26}
27}
28

JPA With ECLIPSE Link Implementattion

If we want to use JPA with EclipseLink implementation then we have to use the following steps.

  • Create JPA project.
  • Create Entity Class with Annotations
  • Create JPA configuration File
  • Create Test Application
  • Create JPA project.
  • Right Click on "Project Explorer".
  • Select on "New".
  • Select "Others"
  • Search and Select JPA Project
  • Click on "Next" button.
  • Provide package name:app6
  • Click on "next" button.
  • Click on "Next" button.
  • Click on "Download Libraries" icon.
  • Select EclipseLink2.5.2 library.
  • Click on "Next" button.
  • Select "Check box" of Accepct Licence of this Aggrement.
  • Click on "Finish" Button.
  • Click on "Finish" button.
  • Click on "Open Perspective".

With these steps JPA project will be created in projects Explorer part..

Create Entity Class with Annotations — Employee.java

Create package "com.durgasoft.entity" under src folder and create Entity class.

Example35
JCode Cell
1 
2package com.durgasoft.entity;
3import java.io.Serializable;
4import java.lang.String;
5import javax.persistence.*;
6@Entity
7@Table(name="emp1")
8public class Employee implements Serializable {
9 
10 
11@Id
12@Column(name="ENO")
13private int eno;
14@Column(name="ENAME")
15private String ename;
16@Column(name="ESAL")
17private float esal;
18@Column(name="EADDR")
19private String eaddr;
20private static final long serialVersionUID = 1L;
21 
22public Employee() {
23super();
24}
25public int getEno() {
26return this.eno;
27}
28 
29public void setEno(int eno) {
30this.eno = eno;
31}
32public String getEname() {
33return this.ename;
34}
35 
36public void setEname(String ename) {
37this.ename = ename;
38}
39public float getEsal() {
40return this.esal;
41}
42 
43public void setEsal(float esal) {
44this.esal = esal;
45}
46public String getEaddr() {
47return this.eaddr;
48}
49 
50public void setEaddr(String eaddr) {
51this.eaddr = eaddr;
52}
53 
54}
55

Create JPA configuration File — persistence.xml

Open persistence.xml file which is existed under"src\META-INF" folder and provide the following details.

Example36
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
4<persistence-unit name="emp">
5<class>com.durgasoft.entity.Employee</class>
6<properties>
7<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
8<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
9<property name="javax.persistence.jdbc.user" value="system"/>
10<property name="javax.persistence.jdbc.password" value="durga"/>
11</properties>
12</persistence-unit>
13</persistence>
14

Create JPA configuration File

  • Create Test Application

Create a package "com.durgasoft.test" and prepare Test class — Test.java

Example38
JCode Cell
1 
2package com.durgasoft.test;
3 
4import javax.persistence.EntityManager;
5import javax.persistence.EntityManagerFactory;
6import javax.persistence.EntityTransaction;
7import javax.persistence.Persistence;
8 
9import com.durgasoft.entity.Employee;
10 
11public class Test {
12 
13public static void main(String[] args)throws Exception {
14EntityManagerFactory factory = Persistence.createEntityManagerFactory("emp");
15EntityManager entityManager = factory.createEntityManager();
16/*
17EntityTransaction entityTransaction = entityManager.getTransaction();
18entityTransaction.begin();
19Employee emp = new Employee();
20emp.setEno(111);
21emp.setEname("AAA");
22emp.setEsal(5000);
23emp.setEaddr("Hyd");
24entityManager.persist(emp);
25entityTransaction.commit();
26System.out.println("Employee Inserted Successfully");
27*/
28/*
29Employee emp = entityManager.find(Employee.class, 111);
30System.out.println("Employee Details");
31System.out.println("------------------------");
32System.out.println("Employee Number :"+emp.getEno());
33System.out.println("Employee Name :"+emp.getEname());
34System.out.println("Employee Salary :"+emp.getEsal());
35System.out.println("Employee Address :"+emp.getEaddr());
36*/
37/*
38EntityTransaction entityTransaction = entityManager.getTransaction();
39entityTransaction.begin();
40Employee emp = entityManager.find(Employee.class, 111);
41emp.setEname("BBB");
42emp.setEsal(7000);
43emp.setEaddr("Sec");
44entityTransaction.commit();
45System.out.println("Employee updated Successfully");
46*/
47EntityTransaction entityTransaction = entityManager.getTransaction();
48entityTransaction.begin();
49Employee emp = entityManager.find(Employee.class, 111);
50entityManager.remove(emp);
51entityTransaction.commit();
52System.out.println("Employee Deleted Successfully");
53entityManager.close();
54}
55}
56

Create a package "com.durgasoft.test" and prepare Test class

Integration of JPA with Spring application in ORM Module

Integration of JPA with Spring application in ORM Module

  • Create Java Project with both Spring Library and Hibernate Library.
  • Create Dao interface
  • Create Dao implementation classs.
  • Create POJO / Entity class.
  • Create Hibernate Mapping File.
  • Create Spring Configuration File.
  • Create Test Application.
  • Create Java Project with both Spring Library and Hibernate Library.

Spring Library

commons-logging-1.2.jar spring-aop-4.3.9.RELEASE.jar spring-beans-4.3.9.RELEASE.jar spring-context-4.3.9.RELEASE.jar spring-context-support-4.3.9.RELEASE.jar spring-core-4.3.9.RELEASE.jar spring-expression-4.3.9.RELEASE.jar spring-jdbc-4.3.9.RELEASE.jar spring-orm-4.3.9.RELEASE.jar spring-tx-4.3.9.RELEASE.jar

Hibernate Library — EmployeeDao.java

hibernate3.jar antlr-2.7.6.jar commons-collections-3.1.jar dom4j-1.6.1.jar javassist-3.12.0.GA.jar jta-1.1.jar slf4j-api-1.6.1.jar hibernate-jpa-2.0-api-1.0.1.Final.jar ojdbc6.jar

  • Create Dao interface
Example42
JCode Cell
1 
2package com.durgasoft.dao;
3
📝 Key Takeaways
  • Key ideas of Spring - ORM Integration (JPA / Hibernate) explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end