Hibernate and Spring Integration

Before knowing Hibernate you must understand JPA.

Introduction

Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes


 Hibernate 

Hibernate is a high-performance Object/Relational persistence and query service which is licensed under the open source GNU Lesser General Public License (LGPL) and is free to download. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities.
This tutorial will teach you how to use Hibernate to develop your database based web applications in simple and easy steps.

JPA and Hibernate Difference
JPA is a specification for accessing, persisting and managing the data between Java objects and the relational database. As the definition says its API, it is only the specification. There is no implementation for the API. JPA specifies the set of rules and guidelines for developing the interfaces that follows standard. Straight to the point : JPA is just guidelines to implement the Object Relational Mapping (ORM)  and there is no underlying code for the implementation.
Where as, Hibernate is the actual implementation of JPA guidelines. When hibernate implements the JPA specification, this will be certified by the JPA group upon following all the standards mentioned in the specification. For example, JPA guidelines would provide information of mandatory and optional features to be implemented as part of the JPA implementation.
Hibernate is a JPA provider.
- See more at: http://www.javabeat.net/jpa-vs-hibernate/#sthash.Qln9BBC6.dpuf
 JPA and Hibernate Difference

JPA is a specification for accessing, persisting and managing the data between Java objects and the relational database. As the definition says its API, it is only the specification. There is no implementation for the API. JPA specifies the set of rules and guidelines for developing the interfaces that follows standard. Straight to the point : JPA is just guidelines to implement the Object Relational Mapping (ORM)  and there is no underlying code for the implementation.

Where as, Hibernate is the actual implementation of JPA guidelines. When hibernate implements the JPA specification, this will be certified by the JPA group upon following all the standards mentioned in the specification. For example, JPA guidelines would provide information of mandatory and optional features to be implemented as part of the JPA implementation.

Hibernate is a JPA provider.

Now we start with our aim  Hibernate and Spring Integration.


We can simply integrate hibernate application with spring application.
In hibernate framework, we provide all the database information hibernate.cfg.xml file.
But if we are going to integrate the hibernate application with spring, we don't need to create the hibernate.cfg.xml file. We can provide all the information in the applicationContext.xml file.

Advantage of Spring framework with hibernate
The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.
So it saves a lot of code.
Understanding problem without using spring:
Let's understand it by the code of hibernate given below:
  1. //creating configuration  
  2. Configuration cfg=new Configuration();    
  3. cfg.configure("hibernate.cfg.xml");    
  4.     
  5. //creating seession factory object    
  6. SessionFactory factory=cfg.buildSessionFactory();    
  7.     
  8. //creating session object    
  9. Session session=factory.openSession();    
  10.     
  11. //creating transaction object    
  12. Transaction t=session.beginTransaction();    
  13.         
  14. Employee e1=new Employee(111,"arun",40000);    
  15. session.persist(e1);//persisting the object    
  16.     
  17. t.commit();//transaction is commited    
  18. session.close();    
As you can see in the code of sole hibernate, you have to follow so many steps.
Solution by using HibernateTemplate class of Spring Framework:
Now, you don't need to follow so many steps. You can simply write this:
  1. Employee e1=new Employee(111,"arun",40000);    
  2. hibernateTemplate.save(e1);

Steps
Let's see what are the simple steps for hibernate and spring integration:
  1. create table in the database It is optional.
  2. create applicationContext.xml file It contains information of DataSource, SessionFactory etc.
  3. create Employee.java file It is the persistent class
  4. create employee.hbm.xml file It is the mapping file.
  5. create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
  6. create InsertTest.java file It calls methods of EmployeeDao class.

Example of Hibernate and spring integration
In this example, we are going to integrate the hibernate application with spring. Let's see the directory structure of spring and hibernate example.

1) create the table in the database In this example, we are using the Oracle as the database, but you may use any database. Let's create the table in the oracle database
  1. CREATE TABLE  "EMP558"   
  2.    (    "ID" NUMBER(10,0) NOT NULL ENABLE,   
  3.     "NAME" VARCHAR2(255 CHAR),   
  4.     "SALARY" FLOAT(126),   
  5.      PRIMARY KEY ("ID") ENABLE  
  6.    )  
  7. /  

2) Employee.java It is a simple POJO class. Here it works as the persistent class for hibernate.
  1. package com.javatpoint;  
  2.   
  3. public class Employee {  
  4. private int id;  
  5. private String name;  
  6. private float salary;  
  7.   
  8. //getters and setters  
  9.   
  10. }  

3) employee.hbm.xml This mapping file contains all the information of the persistent class.
  1. '1.0' encoding='UTF-8'?>  
  2. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4.   
  5. <hibernate-mapping>  
  6. <class name="com.javatpoint.Employee" table="emp558">  
  7.           <id name="id">  
  8.           <generator class="assigned"></generator>  
  9.           </id>  
  10.             
  11.           <property name="name"></property>  
  12.           <property name="salary"></property>  
  13. </class>  
  14.             
  15. </hibernate-mapping>


4) EmployeeDao.java It is a java class that uses the HibernateTemplate class method to persist the object of Employee class.
  1. package com.javatpoint;  
  2. import org.springframework.orm.hibernate3.HibernateTemplate;  
  3.   
  4. public class EmployeeDao {  
  5. HibernateTemplate template;  
  6. public void setTemplate(HibernateTemplate template) {  
  7.     this.template = template;  
  8. }  
  9.   
  10. public void saveEmployee(Employee e){  
  11.     template.save(e);  
  12. }  
  13.   
  14. public void updateEmployee(Employee e){  
  15.     template.update(e);  
  16. }  
  17.   
  18. public void deleteEmployee(Employee e){  
  19.     template.delete(e);  
  20. }  
  21. }  

5) applicationContext.xml In this file, we are providing all the informations of the database in the BasicDataSource object. This object is used in the LocalSessionFactoryBean class object, containing some other informations such as mappingResources and hibernateProperties. The object of LocalSessionFactoryBean class is used in the HibernateTemplate class. Let's see the code of applicationContext.xml file.
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans  
  3.     xmlns="http://www.springframework.org/schema/beans"  
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:p="http://www.springframework.org/schema/p"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  7.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
  8.   
  9.   
  10.     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
  11.         "driverClassName"  value="oracle.jdbc.driver.OracleDriver">
</property>  
  •         <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>  
  •         <property name="username" value="system"></property>  
  •         <property name="password" value="oracle"></property>  
  •     </bean>  
  •       
  •     <bean id="mysessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
  •         "dataSource" ref="dataSource">
  • </property>  
  •           
  •         <property name="mappingResources">  
  •         <list>  
  •         <value>employee.hbm.xml</value>  
  •         </list>  
  •         </property>  
  •           
  •         <property name="hibernateProperties">  
  •             <props>  
  •                 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>  
  •                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  •                 <prop key="hibernate.show_sql">true</prop>  
  •                   
  •             </props>  
  •         </property>  
  •     </bean>  
  •       
  •     <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">  
  •     <property name="sessionFactory" ref="mysessionFactory"></property>  
  •     </bean>  
  •       
  •     <bean id="d" class="com.javatpoint.EmployeeDao">  
  •    <property name="template" ref="template"></property>  
  •     </bean>  
  •       
  •       
  •     </beans> 


  • 6) InsertTest.java This class uses the EmployeeDao class object and calls its saveEmployee method by passing the object of Employee class.
    1. package com.javatpoint;  
    2.   
    3. import org.springframework.beans.factory.BeanFactory;  
    4. import org.springframework.beans.factory.xml.XmlBeanFactory;  
    5. import org.springframework.core.io.ClassPathResource;  
    6. import org.springframework.core.io.Resource;  
    7.   
    8. public class InsertTest {  
    9. public static void main(String[] args) {  
    10.       
    11.     Resource r=new ClassPathResource("applicationContext.xml");  
    12.     BeanFactory factory=new XmlBeanFactory(r);  
    13.       
    14.     EmployeeDao dao=(EmployeeDao)factory.getBean("d");  
    15.       
    16.     Employee e=new Employee();  
    17.     e.setId(114);  
    18.     e.setName("varun");  
    19.     e.setSalary(50000);  
    20.       
    21.     dao.saveEmployee(e);  
    22.       
    23. }  
    24. }  
    Now, if you see the table in the oracle database, record is inserted successfully.

    Enabling automatic table creation, showing sql queries etc.
    You can enable many hibernate properties like automatic table creation by hbm2ddl.auto etc. in applicationContext.xml file. Let's see the code:

              
    1. <property name = "hibernateProperties">
    2.  <props>
    3. <prop key = "hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
    4. <prop key = "hibernate.hbm2ddl.auto">update</prop>
    5. <prop key = "hibernate.show_sql">true</prop>
    6. </props>  
     
       If you write this code, you don't need to create table because table will be created automatically.

    Now this is all about  Hibernate and Spring Integration. Do comment for any quiries.


    Introduction to Java Persistence API(JPA)
    ava Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) a - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    ava Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) a - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Java Persistence API (JPA) provides POJO (Plain Old Java Object) standard and object relational mapping (OR mapping) for data persistence among applications. Persistence, which deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0 as a result of JSR 220. This API has borrowed many of the concepts and standards from leading persistence frameworks like Toplink (from Oracle) and Hibernate (from JBoss). One of the great benefits of JPA is that it is an independent API and can nicely integrate with J2EE as well as J2SE applications. [POJO – Plain Old Java Object is a term used to refer Java objects that do not extend or implement some specialized classes. Therefore, all normal Java objects are POJO’s only. The following classes are not POJO classes - See more at: http://www.javabeat.net/jpa/#sthash.iVuc8t0G.dpuf
    Introduction to Java Persistence API(JPA)
    Introduction to Java Persistence API(JPA)
    Introduction to Java Persistence API(JPA)

    No comments: