Nearby lessons
16 of 35Spring - ORM Integration (JPA / Hibernate)
- 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.
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
Prepare Hibernate Mapping File
- Create DAO interface with persistence methods.
The main intention of DAO interface is to declare all Services.
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.
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:
Prepare Client Application
The main intention of Client Application is to get Dao object and to access Dao object.
Application on Spring-Hibernate integration — Employee.java
Application on Spring-Hibernate integration — EmployeeDao.java
Application on Spring-Hibernate integration — EmployeeDaoImpl.java
Application on Spring-Hibernate integration — Employee.hbm.xml
Application on Spring-Hibernate integration — applicationContext.xml
Application on Spring-Hibernate integration — Test.java
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.
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:
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.
Perform Persistence operation — Test.java
EX:
Simple JPA Example with XML Mapping File — Employee.java
Simple JPA Example with XML Mapping File — Employee.xml
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>
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:
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>
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.
Create JPA configuration File — persistence.xml
Open persistence.xml file which is existed under"src\META-INF" folder and provide the following details.
Create JPA configuration File
- Create Test Application
Create a package "com.durgasoft.test" and prepare Test class — Test.java
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
- Key ideas of Spring - ORM Integration (JPA / Hibernate) explained simply
- Ready-to-use code examples
- Exam-style questions at the end