Hibernate Framework

Hibernate:

  • Given by Gavin King in 2001 as alternate for data-persistent.
  • Hibernate is an open source object relational mapping(ORM) library for the Java language, that provides persistent-classes and logic without caring how to handle the data.
  • Hibernate solves Object-Relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.
  • An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the database.
  • The ORM tool internally uses the JDBC API to interact with the database.
  • It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.





Architecture:


Hibernate vs JDBC:

  Productivity:

           Relational Persistence for JAVA:

Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files/annotation so developer does not need to write code for this.

           Transparent Persistence:

The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

Maintainability:

          Fewer Lines of code:

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects.

          Concentrate on Business logic:


Hibernate lets  you concentrate on Business logic. It provides good API to most common CRUD operations

Performance:

          Support for Query Language:

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax. It also selects an effective way to perform a database manipulation task for an application.

         Optimize Performance through Cache:



Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. With JDBC, caching is maintained by hand-coding.

Security :

        Automatic Versioning and Time Stamping :

By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

Cost effective:

Open-Source, Zero-Cost Product License :
Hibernate is an open source and free to use for both development and production deployments.

Vendor Independent:

            We need not to change Persistency code depending on DB. We can develop on less                             complexity db, can deploy in production on complex DB.


Jdbc and Hibernate Comparisional Diagram:









Jar Used in Hibernate programming:






Connectivity Approach:




   Important class and Interfaces :


  Configuration File:




Hibernate Mapping File(hbm file):


Hibernate Program:




Component Mapping:

In component mapping, it map the dependent object as a component. An component is an object that is stored as an value rather than entity reference. This is mainly used if the dependent object doen't have primary key. It is used in case of composition (HAS-A relation), that is why it is termed as component. Let's see the class that have HAS-A relationship.


package myhibernate;
public class Address
 {
private String city,country;
private int pincode;
//getters and setters
}

package myhibernate;
public class Employee
{
private int id;
private String name;
private Address address;//HAS-A
//getters and setters
}

Here, address is a dependent object. Hibernate framework provides the facility to map the dependent object as a component. Let's see how can we map this dependent object in mapping file.

<class name="myhibernate.Employee" table="Employee_Detail">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>

<component name="address" class="myhibernate.Address">
<property name="city"></property>
<property name="country"></property>
<property name="pincode"></property>
</component>
</class>

Related Table Employee_Detail:


Id
Name
City
Country
PinCode
1
Ankur
New Delhi
India
110019
2
Shashi
Bhagwanpur
India
844114
3
Dev
Delhi
India
11048









Hibernate with Annotation:

Application with Annotation

  • Add the jar file for annotation
  • Create the Persistent class
  • Add mapping of Persistent class in configuration file
  • Create the class that retrieves or stores the persistent objectThe hibernate application can be created with annotation. There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc.
  • Hibernate Annotations are based on the JPA 2 specification and supports all the features.
  • All the JPA annotations are defined in the javax.persistence.* package. Hibernate EntityManager implements the interfaces and life cycle defined by the JPA specification.

Advantage:

  • Don't need to create mapping (hbm) file.
  • Hibernate annotations are used to provide the meta data.


Use of Annotation:

  • @Entity annotation marks this class as an entity.
  • @Table annotation specifies the table name where data of this entity is to be persisted. by-default class name used  as the name of table.Table strategy is also defined using the table annotation.
  • @Id annotation marks the identifier for this entity. It is used to define the nature of id using the attribute of id annotation.
  • @Column annotation specifies the details of the column for this property or field. Property name by-default used as the column name but if we want to change the name of column in table then we can set it accordingly using the attribute of column annotation.



Person.java

package myhibernate;

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

@Entity
@Table(name= "Person_Data")
public class Person {
@Id
private int id;
private String name,address;

public int getId() {
                return id;
}
public void setId(int id) {
                this.id = id;
}
public String getName() {
                return name;
}
public void setName(String name) {
                this.name = name;
}
public String getAddress() {
                return address;
}
public void setAddress(String address) {
                this.address = address;
}


}


Add mapping of Persistent class in configuration file using the <mapping> tag like......

<mapping class="myhibernate.Person"/>



Create the class that retrieves or stores the persistent object,But in main class AnnotationConfiguration class is used in place of Configuration class  to load the hibernate.cfg.xml file.



package myhibernate.Person;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class DemoMain {

SessionFactory factory;
Session session;
Transaction transaction;
AnnotationConfiguration ac=new AnnotaionConfiguration();

void insert()
{
                factory=ac.configure();
                session=factory.openSession();
                transaction=session.beginTransaction();
               
                Person person=new Person();
                person.setId(100);
                person.setName("Shashi");
                person.setAddress("NewDelhi");
               
             
                session.persist(person);
                           
                transaction.commit();
                session.close();
                System.out.println("successfully saved");
}

public static void main(String[] args) {

      DemoMain dm=new DemoMain();
      dm.insert();          
   }
}

..


*************************************************************************

Reach us At: - 0120-4029000 / 24 / 25 / 27 / 29 Mobile: 9953584548
Write us at: - Smruti@apextgi.com and pratap@apextgi.com




2 comments:


  1. Very useful blog. Thanks for the information.

    visit: Hibernate Framework Training

    ReplyDelete
  2. If you're eager to embark on a comprehensive journey into the world of Java Full Stack development, look no further than APTRON's Java Full Stack Course in Noida. This dynamic and industry-focused program is designed to equip you with the skills and knowledge necessary to excel in today's competitive tech landscape. Noida, with its burgeoning IT sector, provides an ideal backdrop for honing your Full Stack expertise.

    ReplyDelete