Friday, 5 May 2017

Hibernate Overview for Beginners

Hibernate Overview:

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA. It is an open source framework created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer lots of  programming tasks. Hibernate acts between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns.

Hibernate Advantages:
  1. Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of code.
  2.  Provides simple APIs for storing and retrieving the Java objects directly to and from database.
  3.  If there is change in the database or in any table, then you only need to change the XML file properties.
  4.  Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java Objects.
  5.  Hibernate does not require an application server to operate on.
  6.  Manipulates Complex associations of objects of your database.
  7.  Minimizes database access with smart fetching strategies.
  8.  Provides simple querying of data.
  9. No need to self create tables.
  10. It creates tables in database according to needs.

Supported Databases:
Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines supported by Hibernate:
  1.  HSQL Database Engine
  2.  Oracle
  3.  Microsoft SQL Server Database
  4.  Sybase SQL Server
  5.  Informix Dynamic Server
  6.  DB2/NT
  7.  MySQL
  8.  PostgreSQL
  9.  FrontBase
Supported Technologies:
Hibernate supports a variety of other technologies, including:
  1.  Eclipse plug-ins
  2.  Maven
  3. XDoclet Spring
  4.  J2EE
Types of objects involved in Hibernate Application Architecture:

Configuration Object:
The Configuration object is the first Hibernate object you create in any Hibernate application. It is usually created only once during application initialization. It basically represents a configuration or properties file required by the Hibernate.

The Configuration object provides two components:

1. Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.

2. Class Mapping Setup: This component creates the connection between the Java classes and database tables.

SessionFactory Object:
Configuration object is used to create a SessionFactory object which in turn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So, if want to use multiple databases, then you would have to create multiple SessionFactory objects.

Session Object:
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

Transaction Object:
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Criteria Object:
Criteria objects are used to create and execute object oriented criteria queries to retrieve objects.
You can download the latest version of hibernate from link given below:
Or If You are using Netbeans 8 IDE you don't need to download it.You can easilt add it while creating your web application.
A ScreenShot of Adding Hibernate to your Application:

Hibernate Tutorial for Beginners

Hibernate Example Using Hibernate One to One Mapping:
You have to first create Configuration file,it looks like:

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/database2</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <mapping resource="cfg/Voter.hbm.xml"/>
    <mapping resource="cfg/Vote.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Don't forget to include this code on top of configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

Then create Hibernate Mapping file:
Vote.hbm.xml-

  <hibernate-mapping>
   <class name="bean.Vote" table="vote">
   <id name="vtid">
      <generator class="foreign">
          <param name="property">voter</param>
   </generator>   
     </id>
          <property name="pname" column="pname"/>
     <property name="cdate" column="cdate"/>
     <one-to-one name="voter" class="bean.Vote"/>      
  </class>
  </hibernate-mapping>


Voter.hbm.xml-
<hibernate-mapping>
  <class name="bean.Voter" table="voter">
  <id name="vid" column="vid"/>
  <property name="name" column="name"/>
  <property name="vage" column="vage"/>
  </class>
</hibernate-mapping>

Also inlcude this code in both mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Then create bean class for Vote:

package bean;
import java.util.Date;
public class Vote 
{
private int vtid;
private String pname;
private Date cdate;
private Voter voter;
    public Vote() {
    }
    public int getVtid() {
        return vtid;
    }
    public void setVtid(int vtid) {
        this.vtid = vtid;
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public Date getCdate() {
        return cdate;
    }
    public void setCdate(Date cdate) {
        this.cdate = cdate;
    }
    public Voter getVoter() {
        return voter;
    }
    public void setVoter(Voter voter) {
        this.voter = voter;
    }
}

Create bean class for Voter:
package bean;
public class Voter {
private int vid;
private String name;
private int vage;
  public Voter() {
    }
    public int getVid() {
        return vid;
    }
    public void setVid(int vid) {
        this.vid = vid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getVage() {
        return vage;
    }
    public void setVage(int vage) {
        this.vage = vage;
    }
}

LAST CREATE TEST CLASS:
package Test;
import bean.Vote;
import bean.Voter;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Test 
{
    public static void main(String[] args) {
        Configuration cfg=new Configuration();
        cfg.configure("cfg/hibernate.cfg.xml");
        SessionFactory sf=cfg.buildSessionFactory();
        Session session=sf.openSession();
        Voter v=new Voter();
        v.setName("balwant");
        v.setVage(24);
        v.setVid(12);
        Vote v1=new Vote();
        v1.setPname("AKP");
        v1.setCdate(new Date());
        v1.setVoter(v);
       Vote v2=new Vote();
        v2.setPname("PPL");
        v2.setCdate(new Date());
        v2.setVoter(v);  
        session.save(v);
        session.save(v1);
       // session.save(v2);
        session.beginTransaction().commit();
        sf.close();
    }
}

Hibernate Session Method:
1. save:hibernate save() can be used to save entity to database. We can invoke this method outside a transaction. If we use this without transaction and we have cascading between entities, then only the primary entity gets saved unless we flush the session.
e.g. session.save(s1);

2.persist: Hibernate persist is similar to save (with transaction) and it adds the entity object to the persistent context, so any further changes are tracked. If the object properties are changed before the transaction is committed or session is flushed, it will also be saved into database.

Second difference is that we can use persist() method only within the boundary of a transaction, so it’s safe and takes care of any cascaded objects.
e.g. session2.persist(emp2);

3.saveOrUpdate: Hibernate saveOrUpdate help in inserting and updating queries based on the provided data. If the data is present in the database, update query is executed.

We can use saveOrUpdate() without transaction also, but you will face the issues with mapped objects not getting saved if session is not flushed.
Hibernate saveOrUpdate adds the entity object to persistent context and track any further changes. Any further changes are saved at the time of committing transaction, like the persist method.
e.g. session.saveOrUpdate(emp);

4.update: Hibernate update must be used there where we know that we are only updating the entity information. This operation adds the entity object to persistent context and further changes are tracked and saved when transaction is committed.
e.g. session.update(emp);

5.merge: Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes. This is the major difference with merge() from all the other methods.
e.g. Employee emp4 = (Employee) session.merge(emp);
Hibernate Lifecycle Of pojo Class Objects:

POJO class object have 3 states which are given below;
  1. Transient state 
  2. Persistent state 
  3. Detached state 
Hibernate tutorial for Beginners

1. Transient State: A New instance of a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate:UserDetail user = new UserDetail(); user.setUserName("BALWANT");

2. Persistent State:
A persistent instance has a representation in the database , an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session:Long id = (Long) session.save(user);

3. Detached State:
Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn't attached to a Session anymore (but can still be modified and reattached to a new Session later though).session.close();


Example: 

import org.hibernate.*;

import org.hibernate.cfg.*;

public class ClientProgram { 

public static void main(String[] args)

{

Configuration cfg = new Configuration();

cfg.configure("hibernate.cfg.xml"); 

SessionFactory factory = cfg.buildSessionFactory();

Session session = factory.openSession();



// Transient state

Product p=new Product();

p.setProductId(101);

p.setProName("MACINTOSH");

p.setPrice(250000);


// Persistent state
Transaction tx = session.beginTransaction();
session.save(p);
System.out.println("Object saved..!!!!!!");
tx.commit();

// Persistent state
session.close();
factory.close();
}


}



Hibernate libraries:

  1. dom4j
  2. Xalan
  3. Xerces
  4. cglib
  5. log4j
  6. Commons
  7. SLF4J
Hibernate Query language:Hibernate Query Language (HQL) is an object-oriented query language, it is similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.Although you can use SQL statements directly with Hibernate using Native SQL but I would suggest you to use HQL whenever there is need of database portability or you can take the advantage of Hibernate's SQL generation and caching strategies.
Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

FROM Clause
You can use FROM clause if you want to load a complete persistent objects into memory. Following is the simple syntax of using FROM clause:

String hql = "FROM Employee";
Query query = session.createQuery(hql);
 List results = query.list();


AS ClauseThe AS clause can be used to assign the  aliases to the classes in your HQL queries, specially when you have very long queries. As from upper example the syntax for the use of as clause can be defined as givern below:

String hql = "FROM Employee AS E";
Query query = session.createQuery(hql); 
List results = query.list();

SELECT Clause
The SELECT clause provides more control over the result set than the FROM clause. If you want to obtain few properties of objects instead of the complete object, you can easilt use the SELECT clause. Following is the simple syntax of using SELECT clause to get just first_name field of the Employee object:

String hql = "SELECT E.lastName FROM Employee E"; 
Query query = session.createQuery(hql); 
List results = query.list();
In this example it will return the lastName of the employee.

WHERE Clause

If you want to narrow the specific objects that are returned from storage, you use the WHERE clause.or we can say that if you want some particulat objects to be retrieved from the database you can go with where clause. Following is the simple syntax of using WHERE clause:

String hql = "FROM Employee E WHERE E.id = 89"; 
Query query = session.createQuery(hql); 
List results = query.list();

ORDER BY Clause
To sort your HQL query's results, you can use the ORDER BY clause. You can order the results by any property on the objects in the result set either ascending (ASC) or descending (DESC). Following is the simple syntax of using ORDER BY clause:

String hql = "FROM Employee E WHERE E.id > 57 ORDER BY E.salary DESC";
Query query = session.createQuery(hql); 
List results = query.list();

In the above example it will return those employees which are having id greater than 57 and they will be order by their salary in descending order.

UPDATE Clause
The UPDATE clause can be used to update one or more properties of an one or more objects. Following is the simple syntax of using UPDATE clause:


String hql = "UPDATE Employee set salary = :salary " + "WHERE id = :employee_id"; 
Query query = session.createQuery(hql); 
query.setParameter("salary", 1000); 
query.setParameter("employee_id", 10); int result = query.executeUpdate();

It will set salary to 100 Where id =10

DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the simple syntax of using DELETE clause:


String hql = "DELETE FROM Employee " + "WHERE id = :employee_id"; 
Query query = session.createQuery(hql); 
query.setParameter("employee_id", 10); 
int result = query.executeUpdate();
System.out.println("No. of Rows affected: " + result);

INSERT Clause
HQL supports INSERT INTO clause only where records can be inserted from one object to another object. Following is the simple syntax of using INSERT INTO clause:

String hql = "INSERT INTO Employee(firstName, lastName, salary,dept)" + "SELECT firstName, lastName, salary.dept FROM bsb_employee"; 
Query query = session.createQuery(hql); 
int result = query.executeUpdate();

No comments:

Post a Comment

Oracle / PLSQL: FOR LOOP

set serveroutput on; declare a1 varchar2(100); begin select count(*) into a1 from employees; for i in 1..a1 loop dbms_output.put_line...