Complete Hibernate 3.0 Tutorial

Hibernate is popular open source object relational mapping tool for Java platform. It provides powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. The Hibernate Query Language, designed as a "minimal" object-oriented extension to SQL, provides an elegant bridge between the object and relational worlds. Hibernate also allows you to express queries using native SQL or Java-based Criteria and Example queries. Hibernate is now the most popular object/relational mapping solution for Java

Introduction to Hibernate 3.0

What is Hibernate?
Hibernate 3.0, the latest Open Source persistence technology at the heart of J2EE EJB 3.0 is available for download from Hibernet.org.The Hibernate 3.0 core is 68,549 lines of Java code together with 27,948 lines of unit tests, all freely available under the LGPL, and has been in development for well over a year. Hibernate maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduces the development time.  Hibernate is not the best solutions for data centric applications that only uses the stored-procedures to implement the business logic in database. It is most useful with object-oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows transparent persistence that enables the applications to switch any database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.

Features of Hibernate

Hibernate Architecture

In this lesson you will learn the architecture of Hibernate.  The following diagram describes the high level architecture of hibernate:

The above diagram shows that Hibernate is using the database and configuration data to provide persistence services (and persistent objects) to the application.

To use Hibernate, it is required to create Java classes that represents the table in the database and then map the instance variable in the class with the columns in the database. Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table. Hibernate automatically creates the query to perform these operations.

Hibernate architecture has three main components:

Hibernate is very good tool as far as object relational mapping is concern, but in terms of connection management and transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate.

Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only uses the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.

Writing First Hibernate Code

In this section I will show you how to create a simple program to insert record in MySQL database. You can run this program from Eclipse or from command prompt as well. I am assuming that you are familiar with MySQL and Eclipse environment.

Configuring Hibernate
In this application Hibernate provided connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.

 

Here is the code:

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

<hibernate-configuration>
<session-factory>
      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">
jdbc:mysql://localhost/hibernatetutorial</property>
      <property name="hibernate.connection.username">
root</property>
      <property name="hibernate.connection.password"></property>
      <property name="hibernate.connection.pool_size">10</property>
      <property name="show_sql">
true</property>
      <property name="dialect">
org.hibernate.dialect.MySQLDialect</property>
      <property name="hibernate.hbm2ddl.auto">
update</property>
      <!-- Mapping files -->
      <mapping resource="
contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

In the above configuration file we specified to use the "hibernatetutorial" which is running on localhost and the user of the database is root with no password. The dialect property  is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database. Hibernate supports many database. With the use of the Hibernate (Object/Relational Mapping and Transparent Object Persistence for Java and SQL Databases),  we can use the following databases dialect type property:

The <mapping resource="contact.hbm.xml"/> property is the mapping for our contact table.

Writing First Persistence Class
Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for Contact.java:

package roseindia.tutorial.hibernate;

/**
 @author Deepak Kumar
 *
 * Java Class to map to the datbase Contact Table
 */
public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

  /**
   @return Email
   */
  public String getEmail() {
    return email;
  }

  /**
   @return First Name
   */
  public String getFirstName() {
    return firstName;
  }

  /** 
   @return Last name
   */
  public String getLastName() {
    return lastName;
  }

  /**
   @param string Sets the Email
   */
  public void setEmail(String string) {
    email = string;
  }

  /**
   @param string Sets the First Name
   */
  public void setFirstName(String string) {
    firstName = string;
  }

  /**
   @param string sets the Last Name
   */
  public void setLastName(String string) {
    lastName = string;
  }

  /**
   @return ID Returns ID
   */
  public long getId() {
    return id;
  }

  /**
   @param l Sets the ID
   */
  public void setId(long l) {
    id = l;
  }

} 

Mapping the Contact Object to the Database Contact table
The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. Here is the code for contact.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </id>

  <property name="firstName">
     <column name="FIRSTNAME" />
  </property>
  <property name="lastName">
    <column name="LASTNAME"/>
  </property>
  <property name="email">
    <column name="EMAIL"/>
  </property>
 </class>
</hibernate-mapping>

Setting Up MySQL Database
In the configuration file(hibernate.cfg.xml) we have specified to use
hibernatetutorial database running on localhost.  So, create the databse ("hibernatetutorial") on the MySQL server running on localhost.

Developing Code to Test Hibernate example
Now we are ready to write a program to insert the data into database. We should first understand about the Hibernate's Session. Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file.  Then the save method on session object is used to save the contact information to the database:

session.save(contact)

Here is the code of FirstExample.java


package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Hibernate example to inset data into Contact table
 */
public class FirstExample {
  public static void main(String[] args) {
    Session session = null;

    try{
      // This step will read hibernate.cfg.xml and prepare hibernate for use
      SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
       session =sessionFactory.openSession();
        //Create new instance of Contact and set values in it by reading them from form object
         System.out.println("Inserting Record");
        Contact contact = new Contact();
        contact.setId(3);
        contact.setFirstName("Deepak");
        contact.setLastName("Kumar");
        contact.setEmail("deepak_38@yahoo.com");
        session.save(contact);
        System.out.println("Done");
    }catch(Exception e){
      System.out.println(e.getMessage());
    }finally{
      // Actual contact insertion will happen at this step
      session.flush();
      session.close();

      }
    
  }
} 

In the next section I will show how to run and test the program.

Running First Hibernate 3.0 Example

Hibernate is free open source software it can be download from http://www.hibernate.org/6.html. Visit the site and download Hibernate 3.0. You can download the Hibernate and install it yourself. But I have provided very thing in one zip file. Download the example code and library from here and extract the content in your favorite directory say "C:\hibernateexample". Download file contains the Eclipse project. To run the example you should have the Eclipse IDE on your machine. Start the Eclipse project and select Java Project as shown below.

Click on "Next" button. In the new screen, enter "hibernateexample" as project name and browse the extracted directory "C:\hibernateexample". 

Click on "Next" button. In the next screen leave the output folder as default "hibernateexample/bin" .

Click on the "Finish" button.

Now Open the FirstExample.java in the editor as show below.

 

Copy  contact.hbm.xml, and hibernate.cfg.xml in the bin directory of the project using windows explorer. To run the example select Run-> Run As -> Java Application from the menu bar as shown below.

This will run the Hibernate example program in Eclipse following output will displayed on the Eclipse Console.

In this section I showed you how to run the our first Hibernate 3.0 example.

Understanding Hibernate O/R Mapping

In the last example we created contact.hbm.xml to map Contact Object to the Contact table in the database. Now let's understand the each component of the mapping file.

 

 

 

 

To recall here is the content of contact.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </id>

  <property name="firstName">
     <column name="FIRSTNAME" />
  </property>
  <property name="lastName">
    <column name="LASTNAME"/>
  </property>
  <property name="email">
    <column name="EMAIL"/>
  </property>
 </class>
</hibernate-mapping>

 

Hibernate mapping documents are simple xml documents. Here are important elements of the mapping file:.

  1. <hibernate-mapping> element
    The first or root element of hibernate mapping document is <hibernate-mapping> element. Between the <
    hibernate-mapping> tag class element(s) are present.
       
  2.  <class> element
    The <Class> element maps the class object with corresponding entity in the database. It also tells what table in the database has to access and what column in that table it should use. Within one <hibernate-mapping> element, several <class> mappings are possible.
      
  3.  <id> element
    The <id> element in unique identifier to identify and object. In fact <id> element map with the primary key of the table. In our code :
    <id name="id" type="long" column="ID" >
    primary key maps to the ID field of the table CONTACT. The attributes of the id element are:
  1. <generator> element
    The
    <generator> method is used to generate the primary key for the new record. Here is some of the commonly used generators :
       
    * Increment - This is used to generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.
       
    *  Sequence - Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.
      
    * Assigned - Assigned method is used when application code generates the primary key. 
       
       
  2. <property> element
    The
    property elements define standard Java attributes and their mapping into database schema. The property element supports the column child element to specify additional properties, such as the index name on a column or a specific column type.

Understanding Hibernate <generator> element

In this lesson you will learn about hibernate <generator> method in detail. Hibernate generator element generates the primary key for new record. There are many options provided by the generator method to be used in different situations.

The <generator> element

This is the optional element under <id> element. The <generator> element is used to specify the class name to be used to generate the primary key for new record while saving a new record. The <param> element is used to pass the parameter (s) to the  class. Here is the example of generator element from our first application:
<generator class="assigned"/>
In this case <generator> element do not generate the primary key and it is required to set the primary key value before calling save() method.

Here are the list of some commonly used generators in hibernates:

Generator

Description

increment

It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.

identity

It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.

seqhilo

The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

guid

It uses a database-generated GUID string on MS SQL Server and MySQL.

native

It picks identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.

select

retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

Using Hibernate <generator> to generate id incrementally

As we have seen in the last section that the increment class generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. In this lesson I will show you how to write running program to demonstrate it. You should not use this method to generate the primary key in case of clustured environment.

In this we will create a new table in database, add mappings in the contact.hbm.xml file, develop the POJO class (Book.java), write the program to test it out.

Create Table in the mysql database:
User the following sql statement to create a new table in the database.
 CREATE TABLE `book` ( 
`id` int(11) NOT NULL default '0', 
`bookname` varchar(50) default NULL, 
PRIMARY KEY (`id`) 
) TYPE=MyISAM

Developing POJO Class (Book.java)
Book.java is our POJO class which is to be persisted to the database table "book".

/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Java Class to map to the database Book table
 */
package roseindia.tutorial.hibernate;


public class Book {
  private long lngBookId;
  private String strBookName;
  
  /**
   @return Returns the lngBookId.
   */
  public long getLngBookId() {
    return lngBookId;
  }
  /**
   @param lngBookId The lngBookId to set.
   */
  public void setLngBookId(long lngBookId) {
    this.lngBookId = lngBookId;
  }
  /**
   @return Returns the strBookName.
   */
  public String getStrBookName() {
    return strBookName;
  }
  /**
   @param strBookName The strBookName to set.
   */
  public void setStrBookName(String strBookName) {
    this.strBookName = strBookName;
  }
} 

Adding Mapping entries to contact.hbm.xml
Add the following mapping code into the contact.hbm.xml file

<class name="roseindia.tutorial.hibernate.Book" table="book">
     <id name="lngBookId" type="long" column="id" >
       
<generator class="increment"/>
     </id>

    <property name="strBookName">
         <column name="bookname" />
     </property>
</class>

 Note that we have used increment for the generator class. *After adding the entries to the xml file copy it to the bin directory of your hibernate eclipse project(this step is required if you are using eclipse).

Write the client program and test it out
Here is the code of our client program to test the application.

/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Example to show the increment class of hibernate generator element to 
 * automatically generate the primay key
 */
package roseindia.tutorial.hibernate;

//Hibernate Imports
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class IdIncrementExample {
  public static void main(String[] args) {
    Session session = null;

    try{
      // This step will read hibernate.cfg.xml and prepare hibernate for use
      SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
      session =sessionFactory.openSession();
       
      org.hibernate.Transaction tx = session.beginTransaction();
       
      //Create new instance of Contact and set values in it by reading them from form object
       System.out.println("Inserting Book object into database..");
      Book book = new Book();
      book.setStrBookName("Hibernate Tutorial");
      session.save(book);
      System.out.println("Book object persisted to the database.");
          tx.commit();
          session.flush();
          session.close();
    }catch(Exception e){
      System.out.println(e.getMessage());
    }finally{
      }
    
  }
} 

To test the program Select Run->Run As -> Java Application from the eclipse menu bar. This will create a new record into the book table.

Hibernate Update Query

In this tutorial we will show how to update a row with new information by retrieving data from the underlying database using the hibernate. Lets first write a java class to update a row to the database.

Create a java class:
Here is the code of our java file (UpdateExample.java), where we will update a field name "InsuranceName" with a value="Jivan Dhara" from a row of the insurance table.

Here is the code of delete query: UpdateExample .java 

package roseindia.tutorial.hibernate;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class UpdateExample {
  /**
   @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Transaction tr = sess.beginTransaction();
      Insurance ins = (Insurance)sess.get(Insurance.class, new Long(1));
      ins.setInsuranceName("Jivan Dhara");
      ins.setInvestementAmount(20000);
      ins.setInvestementDate(new Date());
      sess.update(ins);
      tr.commit();
      sess.close();
      System.out.println("Update successfully!");
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }
} 

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select insurance0_.ID as ID0_0_, insurance0_.insurance_name as insurance2_0_0_, insurance0_.invested_amount as invested3_0_0_, insurance0_.investement_date as investem4_0_0_ from insurance insurance0_ where insurance0_.ID=?

Hibernate: update insurance set insurance_name=?, invested_amount=?, investement_date=? where ID=?

Update successfully!

Hibernate Delete Query

In this lesson we will show how to delete rows from the underlying database using the hibernate. Lets first write a java class to delete a row from the database.

Create a java class:
Here is the code of our java file (DeleteHQLExample.java), which we will delete a row from the insurance table using the query "delete from Insurance insurance where id = 2"

Here is the code of delete query: DeleteHQLExample.java 

package roseindia.tutorial.hibernate;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DeleteHQLExample {
  /**
 @author vinod Kumar
 
 * http://www.roseindia.net Hibernate Criteria Query Example
 *  
 */
  public static void main(String[] args) {
    // TODO Auto-generated method stub  
    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      String hql = "delete from Insurance insurance where id = 2";
      Query query = sess.createQuery(hql);
      int row = query.executeUpdate();
      if (row == 0){
        System.out.println("Doesn't deleted any row!");
      }
      else{
        System.out.println("Deleted Row: " + row);
      }
      sess.close();
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }
} 

                        Hibernate Query Language

Hibernate Query Language or HQL for short is extremely powerful query language. HQL is much like SQL  and are case-insensitive, except for the names of the Java Classes and properties. Hibernate Query Language is used to execute queries against database. Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application. HQL is based on the relational object models and makes the SQL object oriented. Hibernate Query Language uses Classes and properties instead of tables and columns. Hibernate Query Language is extremely powerful and it supports Polymorphism, Associations, Much less verbose than SQL.

There are other options that can be used while using Hibernate. These are Query By Criteria (QBC) and Query BY Example (QBE) using Criteria API and the Native SQL queries. In this lesson we will understand HQL in detail.

Why to use HQL?

 

Understanding HQL Syntax
Any Hibernate Query Language may consist of following elements:

Clauses in the HQL are:

Aggregate functions are:

Subqueries
Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying database supports it.

Preparing table for HQL Examples

In this lesson we will create insurance table and populate it with the data. We will use insurance table for rest of the HQL tutorial.

To create the insurance table and insert the sample data, run the following sql query:


 

 

 

 


/*Table structure for table `insurance` */


drop table if exists `insurance`;


CREATE TABLE `insurance` (

  `ID` int(11) NOT NULL default '0',

  `insurance_name` varchar(50) default NULL,

  `invested_amount` int(11) default NULL,

  `investement_date` datetime default NULL,

  PRIMARY KEY  (`ID`)

) TYPE=MyISAM;


/*Data for the table `insurance` */


insert into `insurance` values (1,'Car Insurance',1000,'2005-01-05 00:00:00');

insert into `insurance` values (2,'Life Insurance',100,'2005-10-01 00:00:00');

insert into `insurance` values (3,'Life Insurance',500,'2005-10-15 00:00:00');

insert into `insurance` values (4,'Car Insurance',2500,'2005-01-01 00:00:00');

insert into `insurance` values (5,'Dental Insurance',500,'2004-01-01 00:00:00');

insert into `insurance` values (6,'Life Insurance',900,'2003-01-01 00:00:00');

insert into `insurance` values (7,'Travel Insurance',2000,'2005-02-02 00:00:00');

insert into `insurance` values (8,'Travel Insurance',600,'2005-03-03 00:00:00');

insert into `insurance` values (9,'Medical Insurance',700,'2005-04-04 00:00:00');

insert into `insurance` values (10,'Medical Insurance',900,'2005-03-03 00:00:00');

insert into `insurance` values (11,'Home Insurance',800,'2005-02-02 00:00:00');

insert into `insurance` values (12,'Home Insurance',750,'2004-09-09 00:00:00');

insert into `insurance` values (13,'Motorcycle Insurance',900,'2004-06-06 00:00:00');

insert into `insurance` values (14,'Motorcycle Insurance',780,'2005-03-03 00:00:00');

Above Sql query will create insurance table and add the following data:

ID

insurance_name

invested_amount

investement_date

1

Car Insurance

1000

2005-01-05 00:00:00

2

Life Insurance

100

2005-10-01 00:00:00

3

Life Insurance

500

2005-10-15 00:00:00

4

Car Insurance

2500

2005-01-01 00:00:00

5

Dental Insurance

500

2004-01-01 00:00:00

6

Life Insurance

900

2003-01-01 00:00:00

7

Travel Insurance

2000

2005-02-02 00:00:00

8

Travel Insurance

600

2005-03-03 00:00:00

9

Medical Insurance

700

2005-04-04 00:00:00

10

Medical Insurance

900

2005-03-03 00:00:00

11

Home Insurance

800

2005-02-02 00:00:00

12

Home Insurance

750

2004-09-09 00:00:00

13

Motorcycle Insurance

900

2004-06-06 00:00:00

14

Motorcycle Insurance

780

2005-03-03 00:00:00

In the future lessons we will use this table to write different HQL examples.

Writing ORM for Insurance table

In this lesson we will write the java class and add necessary code in the contact.hbm.xml file.

Create POJO class:
Here is the code of our java file (Insurance.java), which we will map to the insurance table.


 

 

 

 


package roseindia.tutorial.hibernate;

import java.util.Date;
/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Java Class to map to the database insurance table
 */
public class Insurance {
  private long lngInsuranceId;
  private String insuranceName;
  private int investementAmount;
  private Date investementDate;
  
  /**
   @return Returns the insuranceName.
   */
  public String getInsuranceName() {
    return insuranceName;
  }
  /**
   @param insuranceName The insuranceName to set.
   */
  public void setInsuranceName(String insuranceName) {
    this.insuranceName = insuranceName;
  }
  /**
   @return Returns the investementAmount.
   */
  public int getInvestementAmount() {
    return investementAmount;
  }
  /**
   @param investementAmount The investementAmount to set.
   */
  public void setInvestementAmount(int investementAmount) {
    this.investementAmount = investementAmount;
  }
  /**
   @return Returns the investementDate.
   */
  public Date getInvestementDate() {
    return investementDate;
  }
  /**
   @param investementDate The investementDate to set.
   */
  public void setInvestementDate(Date investementDate) {
    this.investementDate = investementDate;
  }
  /**
   @return Returns the lngInsuranceId.
   */
  public long getLngInsuranceId() {
    return lngInsuranceId;
  }
  /**
   @param lngInsuranceId The lngInsuranceId to set.
   */
  public void setLngInsuranceId(long lngInsuranceId) {
    this.lngInsuranceId = lngInsuranceId;
  }
} 

Adding mappings into  contact.hbm.xml file
Add the following code into  contact.hbm.xml file.

 <class name="roseindia.tutorial.hibernate.Insurance" table="insurance">

                <id name="lngInsuranceId" type="long" column="ID" >

                        <generator class="increment"/>

                </id>


                <property name="insuranceName">

                        <column name="insurance_name" />

                </property>

                <property name="investementAmount">

                        <column name="invested_amount" />

                </property>

                <property name="investementDate">

                        <column name="investement_date" />

                </property>

        </class>

     

     

Now we have created the POJO class and necessary mapping into contact.hbm.xml file

HQL from clause Example

The from clause

        The simplest possible Hibernate query is of the form:

                From org.applabs.base.User

                From User

This simply returns all instances of the class org.applabs.base.User.

Most of the time, you will need to assign an alias, since you will want to refer to the User in other parts of the query.

        from User as user

This query assigns the alias user to User instances, so we could use that alias later in the query. The as keyword is optional; we could also write:

        from User user

Multiple classes may appear, resulting in a cartesian product or "cross" join.

from User, Group

from User as user, Group as group

In this example you will learn how to use the HQL from clause. The from clause is the simplest possible Hibernate Query. Example of from clause is:

from Insurance insurance

Here is the full code of the from clause example:


 

 

 

 


package roseindia.tutorial.hibernate;

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

import java.util.*;

/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Select HQL Example
 */
public class SelectHQLExample {

  public static void main(String[] args) {
  Session session = null;

  try{
    // This step will read hibernate.cfg.xml and prepare hibernate for use
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
     session =sessionFactory.openSession();
     
     
      //Using from Clause
       String SQL_QUERY ="from Insurance insurance";
       Query query = session.createQuery(SQL_QUERY);
       for(Iterator it=query.iterate();it.hasNext();){
         Insurance insurance=(Insurance)it.next();
         System.out.println("ID: " + insurance.getLngInsuranceId());
         System.out.println("First Name: " + insurance.getInsuranceName());
       }
       
          session.close();
  }catch(Exception e){
    System.out.println(e.getMessage());
  }finally{
    }

  }  
} 

 

Hibernate Select Clause

 The select clause picks which objects and properties  to return in the query result set. Queries may return properties of any value type including properties of component type:

select user.name from User user

where user.name like 'mary%'

select customer.contact.firstName from Customer as cust

In this lesson we will write example code to select the data from Insurance table using Hibernate Select Clause. The select clause picks up objects and properties to return in the query result set. Here is the query:

Select insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate from Insurance insurance

which selects all the rows (insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate) from Insurance table.

Hibernate generates the necessary sql query and selects all the records from Insurance table. Here is the code of our java file which shows how select HQL can be used:


package roseindia.tutorial.hibernate;

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

import java.util.*;

/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * HQL Select Clause Example
 */
public class SelectClauseExample {
  public static void main(String[] args) {
  Session session = null;

  try{
    // This step will read hibernate.cfg.xml and prepare hibernate for use
    SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();

    session = sessionFactory.openSession();
     
    //Create Select Clause HQL
     String SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," 
     "insurance.investementAmount,insurance.investementDate from Insurance insurance";
     Query query = session.createQuery(SQL_QUERY);
     for(Iterator it=query.iterate();it.hasNext();){
       Object[] row = (Object[]) it.next();
       System.out.println("ID: " + row[0]);
       System.out.println("Name: " + row[1]);
       System.out.println("Amount: " + row[2]);
     }
     
        session.close();
  }catch(Exception e){
    System.out.println(e.getMessage());
  }finally{
    }
  }
} 

The where clause

The where clause allows you to narrow the list of instances returned.

from User as user where user.name='mary'

        returns instances of User named 'mary'.

Compound path expressions make the where clause extremely powerful. Consider:

from org.applabs.base.Customer cust where cust.contact.name is not null

This query translates to an SQL query with a table (inner) join. If you were to write something like

The = operator may be used to compare not only properties, but also instances:

from Document doc, User user where doc.user.name = user.name

The special property (lowercase) id may be used to reference the unique identifier of an object. (You may also use its property name.)

from Document as doc where doc.id = 131512

from Document as doc where doc.author.id = 69

The order by clause

The list returned by a query may be ordered by any property of a returned class or components:

from User user order by user.name asc, user.creationDate desc, user.email

       The optional asc or desc indicate ascending or descending order respectively.

The group by clause

A query that returns aggregate values may be grouped by any property of a returned class or components:

select sum(document) from Document document group by document.category

A having clause is also allowed.

select sum(document) from Document document group by document.category

having document.category in (Category.HIBERNATE, Category.STRUTS)

Associations and joins

We may also assign aliases to associated entities, or even to elements of a collection of values, using a join. The supported join types are borrowed from ANSI SQL

• inner join

• left outer join

• right outer join

• full join (not usually useful)

The inner join, left outer join and right outer join constructs may be abbreviated.

Aggregate functions

HQL queries may even return the results of aggregate functions on properties: The supported aggregate functions are

avg(...), sum(...), min(...), max(...) , count(*), count(...), count(distinct ...), count(all...)

The distinct and all keywords may be used and have the same semantics as in SQL.

Expressions

Expressions allowed in the where clause include most of the kind of things you could write in SQL:

• mathematical operators +, -, *, /

• binary comparison operators =, >=, <=, <>, !=, like

• logical operations and, or, not

• string concatenation ||

• SQL scalar functions like upper() and lower()

• Parentheses ( ) indicate grouping

• in, between, is null

• JDBC IN parameters ?

• named parameters :name, :start_date, :x1

• SQL literals 'foo', 69, '1970-01-01 10:00:01.0'

• Java public static final constants eg.Color.TABBY

Sub queries

For databases that support subselects, Hibernate supports subqueries within queries. A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed.

Hibernate Count Query

In this section we will show you, how to use the Count Query. Hibernate supports multiple aggregate functions. when they are used in HQL queries, they return an aggregate value (such as sum, average, and count) calculated from property values of all objects satisfying other query criteria. These functions can be used along with the distinct and all options, to return aggregate values calculated from only distinct values and all values (except null values), respectively. Following is a list of aggregate functions with their respective syntax; all of them are self-explanatory.

count( [ distinct | all ] object | object.property )

count(*)     (equivalent to count(all ...), counts null values also)

sum ( [ distinct | all ] object.property)

avg( [ distinct | all ] object.property)

max( [ distinct | all ] object.property)

min( [ distinct | all ] object.property) 

Here is the java code for counting the records from insurance table:

package roseindia.tutorial.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateHQLCountFunctions {

  /**
   
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session sess = null;
    int count = 0;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      String SQL_QUERY = "select count(*)from Insurance insurance group by 
insurance.lngInsuranceId"
;
        Query query = sess.createQuery(SQL_QUERY);
        for (Iterator it = query.iterate(); it.hasNext();) {
          it.next();
            count++;
        }
        System.out.println("Total rows: " + count);
      sess.close();
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }

} 

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select count(*) as col_0_0_ from insurance insurance0_ group by insurance0_.ID

Total rows: 6

Hibernate Avg() Function (Aggregate Functions)

In this section, we will show you, how to use the avg() function. Hibernate supports multiple aggregate functions. When they are used in HQL queries, they return an aggregate value ( such as avg(...), sum(...), min(...), max(...) , count(*), count(...), count(distinct ...), count(all...) ) calculated from property values of all objects satisfying other query criteria. 

Following is a aggregate function (avg() function) with their respective syntax.

avg( [ distinct | all ] object.property):

The avg() function aggregates the average value of the given column. 

Table Name: insurance

ID

insurance_name

invested_amount

investement_date

2

Life Insurance

25000

0000-00-00 00:00:00

1

Givan Dhara

20000 

2007-07-30 17:29:05

3

Life Insurance

  500

2005-10-15 00:00:00

4

Car Insurance 

  2500

2005-01-01 00:00:00

5

Dental Insurance

500

2004-01-01 00:00:00

Life Insurance

900

2003-01-01 00:00:00

Travel Insurance

  2000 

2005-02-02 00:00:00

Here is the java code to retrieve the average value of "invested_amount" column from insurance table:

package roseindia.tutorial.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateHQLAvgFunction {

  /**
   * @Vinod kumar
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      String SQL_QUERY = "select avg(investementAmount) from Insurance insurance";
      Query query = sess.createQuery(SQL_QUERY);
      List list = query.list();
      System.out.println("Average of Invested Amount: " + list.get(0));
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }

} 

Download this Code.

Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select avg(insurance0_.invested_amount) as col_0_0_ from insurance insurance0_

Average of Invested Amount: 7342.8571

Hibernate Max() Function (Aggregate Functions)

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      String SQL_QUERY = "select max(investementAmount)from Insurance insurance";
        Query query = sess.createQuery(SQL_QUERY);
        List list = query.list();
        System.out.println("Max Invested Amount: " + list.get(0));   
      sess.close();
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }

Hibernate Min() Function (Aggregate Functions)

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      String SQL_QUERY = "select min(investementAmount) from Insurance insurance";
      Query query = sess.createQuery(SQL_QUERY);
      List list = query.list();
      System.out.println("Min Invested Amount: " + list.get(0));
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }

HQL Where Clause Example

public class WhereClauseExample {
  public static void main(String[] args) {
  Session session = null;

  try{
    // This step will read hibernate.cfg.xml and prepare hibernate for use
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    session =sessionFactory.openSession();
     
      System.out.println("*******************************");
      System.out.println("Query using Hibernate Query Language");
    //Query using Hibernate Query Language
     String SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1'";
     Query query = session.createQuery(SQL_QUERY);
     for(Iterator it=query.iterate();it.hasNext();){
       Insurance insurance=(Insurance)it.next();
       System.out.println("ID: " + insurance.getLngInsuranceId());
       System.out.println("Name: " + insurance.getInsuranceName());
       
     }
     System.out.println("*******************************");
     System.out.println("Where Clause With Select Clause");
    //Where Clause With Select Clause
     SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," +
     "insurance.investementAmount,insurance.investementDate from Insurance insurance "
    " where insurance.lngInsuranceId='1'";
     query = session.createQuery(SQL_QUERY);
     for(Iterator it=query.iterate();it.hasNext();){
       Object[] row = (Object[]) it.next();
       System.out.println("ID: " + row[0]);
       System.out.println("Name: " + row[1]);
       
     }
     System.out.println("*******************************");

        session.close();
  }catch(Exception e){
    System.out.println(e.getMessage());
  }finally{
    }    
  }
}

HQL Group By Clause Example

Group by clause is used to return the aggregate values by grouping on returned component. HQL supports Group By Clause. In our example we will calculate the sum of invested amount in each insurance type. Here is the java code for calculating the invested amount insurance wise:

public class HQLGroupByExample {
  public static void main(String[] args) {
    Session session = null;
    try {
      // This step will read hibernate.cfg.xml and prepare hibernate fo         //  r  use
      SessionFactory sessionFactory = new Configuration().configure()
          .buildSessionFactory();
      session = sessionFactory.openSession();
      //Group By Clause Example
      String SQL_QUERY = "select sum(insurance.investementAmount),insurance.insuranceName "
          "from Insurance insurance group by insurance.insuranceName";
      Query query = session.createQuery(SQL_QUERY);
      for (Iterator it = query.iterate(); it.hasNext();) {
        Object[] row = (Object[]) it.next();
        System.out.println("Invested Amount: " + row[0]);
        System.out.println("Insurance Name: " + row[1]);
      }
      session.close();
    catch (Exception e) {
      System.out.println(e.getMessage());
    finally {
    }
  }
}

HQL Order By Example

Order by clause is used to retrieve the data from database in the sorted order by any property of returned class or components. HQL supports Order By Clause. In our example we will retrieve the data sorted on the insurance type. Here is the java example code:

public class HQLOrderByExample {
  public static void main(String[] args) {
    Session session = null;
    try {
      // This step will read hibernate.cfg.xml and prepare hibernate for
      // use
      SessionFactory sessionFactory = new Configuration().configure()
          .buildSessionFactory();
      session = sessionFactory.openSession();
      //Order By Example
      String SQL_QUERY = " from Insurance as insurance order by insurance.insuranceName";
      Query query = session.createQuery(SQL_QUERY);
      for (Iterator it = query.iterate(); it.hasNext();) {
        Insurance insurance = (Insurance) it.next();
        System.out.println("ID: " + insurance.getLngInsuranceId());
        System.out.println("Name: " + insurance.getInsuranceName());
      }
      session.close();
    catch (Exception e) {
      System.out.println(e.getMessage());
    finally {
    }
  }
}

                        Hibernate Criteria Query

The Criteria interface allows to create and execute object-oriented queries. It is powerful alternative to the HQL but has own limitations. Criteria Query is used mostly in case of multi criteria search screens, where HQL is not very effective. 

The interface org.hibernate.Criteria is used to create the criterion for the search. The org.hibernate.Criteria interface represents a query against a persistent class. The Session is a factory for Criteria instances. Here is a simple example of Hibernate Criterial Query:

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
 @author Deepak Kumar
 
 * http://www.roseindia.net Hibernate Criteria Query Example
 *  
 */public class HibernateCriteriaQueryExample {
  public static void main(String[] args) {
    Session session = null;
    try {
      // This step will read hibernate.cfg.xml and prepare hibernate for
      // use
      SessionFactory sessionFactory = new Configuration().configure()
          .buildSessionFactory();
      session = sessionFactory.openSession();
      //Criteria Query Example
      Criteria crit = session.createCriteria(Insurance.class);
      List insurances = crit.list();
      for(Iterator it = insurances.iterator();it.hasNext();){
        Insurance insurance = (Insurance) it.next();
        System.out.println("ID: " + insurance.getLngInsuranceId());
        System.out.println("Name: " + insurance.getInsuranceName());
        
      }
      session.close();
    catch (Exception e) {
      System.out.println(e.getMessage());
    finally {
    }    
  }
} 

The above Criteria Query example selects all the records from the table and displays on the console. In the above code the following code creates a new Criteria instance, for the class Insurance:

Criteria crit = session.createCriteria(Insurance.class);

The code:

List insurances = crit.list();

creates the sql query and execute against database to retrieve the data.

Criteria Query Examples

In the last lesson we learnt how to use Criteria Query to select all the records from Insurance table. In this lesson we will learn how to restrict the results returned from the database. Different method provided by Criteria interface can be used with the help of Restrictions to restrict the records fetched from database.


 

 

 

Criteria Interface provides the following methods:

Method

Description

add

The Add method adds a Criterion to constrain the results to be retrieved.

addOrder

Add an Order to the result set.

createAlias

Join an association, assigning an alias to the joined entity

createCriteria

This method is used to create a new Criteria, "rooted" at the associated entity.

setFetchSize

This method is used to set a fetch size for the underlying JDBC query.

setFirstResult

This method is used to set the first result to be retrieved.

setMaxResults

This method is used to set a limit upon the number of objects to be retrieved.

uniqueResult
          

This method is used to instruct the Hibernate to fetch and return the unique records from database.

Class Restriction provides built-in criterion via static factory methods. Important methods of the Restriction class are:

Method

Description

Restriction.allEq
          

This is used to apply an "equals" constraint to each property in the key set of a Map

Restriction.between
          

This is used to apply a "between" constraint to the named property

Restriction.eq
          

This is used to apply an "equal" constraint to the named property

Restriction.ge
          

This is used to apply a "greater than or equal" constraint to the named property

Restriction.gt
          

This is used to apply a "greater than" constraint to the named property

Restriction.idEq

This is used to apply an "equal" constraint to the identifier property

Restriction.ilike
          

This is case-insensitive "like", similar to Postgres ilike operator

Restriction.in

This is used to apply an "in" constraint to the named property

Restriction.isNotNull

This is used to apply an "is not null" constraint to the named property

Restriction.isNull          

This is used to apply an "is null" constraint to the named property

Restriction.le         

This is used to apply a "less than or equal" constraint to the named property

Restriction.like

This is used to apply a "like" constraint to the named property

Restriction.lt

This is used to apply a "less than" constraint to the named property

Restriction.ltProperty

This is used to apply a "less than" constraint to two properties

Restriction.ne         

This is used to apply a "not equal" constraint to the named property

Restriction.neProperty

This is used to apply a "not equal" constraint to two properties

Restriction.not  

This returns the negation of an expression

Restriction.or

 This returns the disjuction of two expressions

Here is an example code that shows how to use Restrictions.like method and restrict the maximum rows returned by query by setting the Criteria.setMaxResults() value to 5.

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
 @author Deepak Kumar
 
 * http://www.roseindia.net Hibernate Criteria Query Example
 *  
 */public class HibernateCriteriaQueryExample2 {
  public static void main(String[] args) {
    Session session = null;
    try {
      // This step will read hibernate.cfg.xml and prepare hibernate for
      // use
      SessionFactory sessionFactory = new Configuration().configure()
          .buildSessionFactory();
      session = sessionFactory.openSession();
      //Criteria Query Example
      Criteria crit = session.createCriteria(Insurance.class);
      crit.add(Restrictions.like("insuranceName""%a%")); //Like condition
      crit.setMaxResults(5); //Restricts the max rows to 5

      List insurances = crit.list();
      for(Iterator it = insurances.iterator();it.hasNext();){
        Insurance insurance = (Insurance) it.next();
        System.out.println("ID: " + insurance.getLngInsuranceId());
        System.out.println("Name: " + insurance.getInsuranceName());
        
      }
      session.close();
    catch (Exception e) {
      System.out.println(e.getMessage());
    finally {
    }    
  }
} 

Hibernate's Built-in criterion: Between (using Integer) 

In this tutorial,, you will learn to use "between" with the Integer class. "Between" when used with the Integer object, It takes three parameters e.g.  between("property_name",min_int,max_int).

Restriction class provides built-in criterion via static factory methods. One important  method of the Restriction class is
between : which is used to apply a "between" constraint to the named property

Here is the code of the class using "between" with the Integer class :

public static void main(String[] args) {
    Session session = null;
    try {
      // This step will read hibernate.cfg.xml and prepare hibernate for
      // use
      SessionFactory sessionFactory = new Configuration().configure()
          .buildSessionFactory();
      session = sessionFactory.openSession();
      //Criteria Query Example
      Criteria crit = session.createCriteria(Insurance.class);
      crit.add(Expression.between("investementAmount"new Integer(1000),
               
new Integer(2500))); //Between condition
      crit.setMaxResults(5); //Restricts the max rows to 5

      List insurances = crit.list();
      for(Iterator it = insurances.iterator();it.hasNext();){
        Insurance insurance = (Insurance) it.next();
        System.out.println("ID: " + insurance.getLngInsuranceId());
        System.out.println("Name: " + insurance.getInsuranceName());
        System.out.println("Amount: " + insurance.getInvestementAmount());
        
      }
      session.close();
    catch (Exception e) {
      System.out.println(e.getMessage());
    finally {
    }    
  }

Hibernate's Built-in criterion: Between (using with Date) 

In this section, you will learn to use "between" i.e.one of the built-in hibernate criterions. Restriction  class  provides built-in criterion via static factory methods. One important  method of the Restriction class is between : which is used to apply a "between" constraint to the named property

In this tutorial, "Between" is used with the date object. It takes three parameters e.g.  between("property_name",startDate,endDate)

public static void main(String[] args) {
    Session session = null;
    try {
      // This step will read hibernate.cfg.xml and prepare hibernate for
      // use
      SessionFactory sessionFactory = new Configuration().configure()
          .buildSessionFactory();
      session = sessionFactory.openSession();
      //Criteria Query Example
      Criteria crit = session.createCriteria(Insurance.class);
      DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      Date startDate = (Date)format.parse("2005-01-01 00:00:00");
      Date endDate = (Date)format.parse("2005-03-03 00:00:00");
      crit.add(Expression.between("investementDate"new Date(startDate.getTime()),
 
new Date(endDate.getTime()))); //Between date condition
      crit.setMaxResults(5); //Restricts the max rows to 5

      List insurances = crit.list();
      for(Iterator it = insurances.iterator();it.hasNext();){
        Insurance insurance = (Insurance) it.next();
        System.out.println("ID: " + insurance.getLngInsuranceId());
        System.out.println("Name: " + insurance.getInsuranceName());
        System.out.println("Amount: " + insurance.getInvestementAmount());
        System.out.println("Date: " + insurance.getInvestementDate());
        
      }
      session.close();
    catch (Exception e) {
      System.out.println(e.getMessage());
    finally {
    }    
  }

Hibernate Criteria Expression (eq)

In this section, you will learn to use the "eq" method. This is one of the most important  method that is used to apply an "equal" constraint to the named property.

Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports eq() method in Expression class.

In this tutorial, "Eq" is used with the date object. It takes two parameters e.g.  eq("property_name",Object val).

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session sess = null;
    try{
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Criteria crit = sess.createCriteria(Insurance.class);
      DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = (Date)format.parse("2005-01-01 00:00:00");
      crit.add(Expression.eq("investementDate",date));
      List list = crit.list();
      for(Iterator it = list.iterator();it.hasNext();){
        Insurance ins = (Insurance)it.next();
        System.out.println("Id: " + ins.getLngInsuranceId());
        System.out.println("Insurance Name: " + ins.getInsuranceName());
        System.out.println("Insurance Amount: " + ins.getInvestementAmount());
        System.out.println("Investement Date: " + ins.getInvestementDate());
      }
      sess.clear();
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }

Hibernate Criteria Expression (lt)

In this section, you will learn to use the "lt" method. This is one of the most important  method that is used to apply a "less than" constraint to the named property.

Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports lt() method in Expression class.

In this tutorial, "lt" is used with the Integer object (invested_amount). It takes two parameters e.g.  lt("property_name",Object val).

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.lt("investementAmount",new Integer(900)));
      List list = crit.list();
      for (Iterator it = list.iterator();it.hasNext();){
        Insurance ins = (Insurance)it.next();
        System.out.println("Insurance Id: "  + ins.getLngInsuranceId());
        System.out.println("Insurance Name: " + ins.getInsuranceName());
        System.out.println("Insurance Amount: " + ins.getInvestementAmount());
        System.out.println("Investement Date: " + ins.getInvestementDate());
      }
      sess.close();
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }

Hibernate Criteria Expression (le)

In this section, you will learn to use the "le" method. This is one of the most important  method that is used to apply a "less than or equal" constraint to the named property.

Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports le() method in Expression class.

In this tutorial, "le" is used with the Integer object (invested_amount). It takes two parameters e.g.  le("property_name",Object val).

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.le("investementAmount",new Integer(900)));
      List list = crit.list();
      for (Iterator it = list.iterator();it.hasNext();){
        Insurance ins = (Insurance)it.next();
        System.out.println("Insurance Id: "  + ins.getLngInsuranceId());
        System.out.println("Insurance Name: " + ins.getInsuranceName());
        System.out.println("Insurance Amount: " + ins.getInvestementAmount());
        System.out.println("Investement Date: " + ins.getInvestementDate());
      }
      sess.close();
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }

Hibernate Criteria Expression (gt)

In this section, you will learn to use the "gt" method. This is one of the most important  method that is used to apply a "greater than" constraint to the named property

Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports gt() method in Expression class.

In this tutorial, "gt" is used with the Long object (ID). It takes two parameters e.g.  ge("property_name",Object val).

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Session sess = null;
    try {
      SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.gt("lngInsuranceId",new Long(3)));
      List list = crit.list();
      for (Iterator it = list.iterator();it.hasNext();){
        Insurance ins = (Insurance)it.next();
        System.out.println("Insurance Id: "  + ins.getLngInsuranceId());
        System.out.println("Insurance Name: " + ins.getInsuranceName());
        System.out.println("Insurance Amount: " + ins.getInvestementAmount());
        System.out.println("Investement Date: " + ins.getInvestementDate());
      }
      sess.close();
    }
    catch(Exception e){
      System.out.println(e.getMessage());
    }
  }

Simlarly we can use

Hibernate Criteria Expression (ge)

In this section, you will learn to use the "ge" method. This is one of the most important  method that is used to apply a "greater than or equal" constraint to the named property.

Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports ge() method in Expression class.

In this tutorial, "ge" is used with the Long object (ID). It takes two parameters e.g.  ge("property_name",Object val).


    Criteria crit = sess.createCriteria(Insurance.class);
        crit.add(Expression.ge("lngInsuranceId",new Long(3)));
        List list = crit.list();

Hibernate Criteria Expression (and)

In this section, you will learn to use the "and" method. This is one of the most important  method that returns the conjunctions of two expressions. You can also build the nested expressions using 'and' and 'or'. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. 

Expression and(Criterion LHS, Criterion RHS): This method returns the conjunctions of two expressions. Both conditions are 'true' then it xecutes the query otherwise not. In this tutorial, "and" is used :

Expression.and(Expression.gt("lngInsuranceId", new Long(3), Expression.lt("IngInsuranceId", new Long(6))).

Example:

SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.and(Expression.gt("lngInsuranceId",new Long(3)),
                                   Expression.lt(
"lngInsuranceId",new Long(6))));
      List list = crit.list();

Hibernate Criteria Expression (or)

In this section, you will learn to use the "or" method. This is one of the most important  method that returns the disjunction of the two expressions. You can also build the nested expressions using 'and' and 'or'. 
Expressions:
 The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. 

Expression or(Criterion LHS, Criterion RHS): This method returns the disjuction of two expressions. Any given condition is 'true' then it executes the query. In this tutorial, "or" is used :

Expression.or(Expression.eq("lngInsuranceId", new Long(3), Expression.eq("IngInsuranceId", new Long(6))).

SessionFactory fact = new Configuration().configure().buildSessionFactory();
      sess = fact.openSession();
      Criteria crit = sess.createCriteria(Insurance.class);
      crit.add(Expression.or(Expression.eq("lngInsuranceId",new Long(3)),
                                   Expression.eq(
"lngInsuranceId",new Long(6))));
      List list = crit.list();

                        Hibernate Native SQL

Native SQL is handwritten SQL for all database operations like create, update, delete and select. Hibernate Native Query also supports stored procedures. Hibernate allows you to run Native SQL Query for all the database operations, so you can use your existing handwritten sql with Hibernate, this also helps you in migrating your SQL/JDBC based application to Hibernate.

In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to calculate average and then in another example select all the objects from table.

Here is the code of Hibernate Native SQL:

package roseindia.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
 @author Deepak Kumar
 
 * http://www.roseindia.net Hibernate Native Query Example
 *  
 */
public class NativeQueryExample {
  public static void main(String[] args) {
    Session session = null;

    try{
      // This step will read hibernate.cfg.xml and prepare hibernate for use
      SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
      session =sessionFactory.openSession();
      /* Hibernate Native Query Average Examle*/
       String sql ="select stddev(ins.invested_amount) as stdErr, "+
         " avg(ins.invested_amount) as mean "+
         " from insurance ins";
       Query query = session.createSQLQuery(sql).addScalar("stdErr",Hibernate.DOUBLE).
         addScalar("mean",Hibernate.DOUBLE);
       //Double [] amount = (Double []) query.uniqueResult(); 
       Object [] amount = (Object []) query.uniqueResult(); 
       System.out.println("mean amount: " + amount[0]);
       System.out.println("stdErr amount: " + amount[1]);

       /* Example to show Native query to select all the objects from database */
       /* Selecting all the objects from insurance table */
       List insurance = session.createSQLQuery("select  {ins.*}  from insurance ins")
      .addEntity("ins", Insurance.class)
        .list();
      for (Iterator it = insurance.iterator(); it.hasNext();) {
        Insurance insuranceObject = (Insurance) it.next();
        System.out.println("ID: " + insuranceObject.getLngInsuranceId());
        System.out.println("Name: " + insuranceObject.getInsuranceName());
      }
      
          session.close();
    }catch(Exception e){
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
    
  }
} 

Following query is used to calculate the average of  invested amount:

/*Hibernate Native Query Average Examle*/

String sql ="select stddev(ins.invested_amount) as stdErr, "+ " avg(ins.invested_amount) as mean "+ " from insurance ins";

The following code:

Query query = session.createSQLQuery(sql).addScalar("stdErr",Hibernate.DOUBLE).
addScalar("mean",Hibernate.DOUBLE);

Creates a new instance of SQLQuery for the given SQL query string and the entities returned by the query are detached. 

To return all the entities from database we have used the following query:

/* Example to show Native query to select all the objects from database */
/* Selecting all the objects from insurance table */
List insurance = session.createSQLQuery("
select {ins.*} from insurance ins")
.addEntity("
ins", Insurance.class)
.list();
    for (Iterator it = insurance.iterator(); it.hasNext();) {
    Insurance insuranceObject = (Insurance) it.next();
    System.out.println("ID: " + insuranceObject.getLngInsuranceId());
   System.out.println("Name: " + insuranceObject.getInsuranceName());
}

Hibernate Types

This section gives you description of all the Types that are supported by Hibernate. A Hibernate Type is used to map a Java property type to a JDBC type or types. 

The following tables to represents all Hibernate types:

Interfaces and Descriptions:

AbstractComponentType

The AbstractComponentType enables other Component-like types to hold collections and have cascades, etc.

AssociationType

This interface used to represent all associations between entities.

DiscriminatorType

This interface used to discriminator properties with the help of right mapped subclass.

IdentifierType

This interface has All identifiers of entities.

LiteralType

This is a maker interface that which store SQL literals.

Type

This interface describes mapping between the Java and JDBC datatypes

VersionType

This interface used for version stamping.

 

Classes and Descriptions:

AbstractBynaryType

The stream of byte bounded into a VAQRBINARY.

AbstractCharArrayType

The stream of char bounded into a VARCHAR.

AbstractType

This is a superclass that can be used for creating type hierarchy.

AdaptedImmutableType

AnyType

It defines 'any' mappings and deprecated 'object' types.

AnyType.ObjectTypeCacheEntry

ArrayType

It represents collection of data into a similar types.

BagType

BigDecimaType

This class used to mapping between SQL NUMERIC and java.math.BigDecimal.

BigIntegerType

This class used to mapping between SQL NUMERIC and java.math.BigInteger.

BinaryType

It used to mapping between a SQL VARBINARY and a Java byte[]. 

BlobType

It used to mapping between a SQL BLOB and java.sql.Blob.

BooleanType

This class maps between SQL BIT and Java Boolean.

ByteType

This class maps between SQL TINYINT  and Java Byte.

CalendarDateType

This class represents a data and mapping into a Calendar object.

CalendarType

It also represents a datetime mapping into a Calendar object.

CharacterArrayType

It is a collection of VARCHAR like: Character[].

CharacterType

This class mapping between a SQL CHAR and a Java Character.

CharArrayType

It is a collection of VARCHAR like: char[].

CharBooleanType

This is a superclass that can be mapping between SQL CHAR and Java boolean.

ClassType

This class mapping between SQL VARCHAR and Java class.

ClobType

This class mapping between SQL CLOB and java.sql.Clob.

CollectionType

It handles the Hibernate PersistentCollections.

ComponentType

This class mapping all components.

CompositeCustomType

It adjusts CompositeUserType to Type interface.;

CurrencyType

It is used to mapping a SQL VARCHAR into a java.util.Currency.

CustomCollectionType

This class is created by users and implement the PersistentCollection.

CustomType

It adjusts the user type to generic type interface and changes the internal type contracts.

DateType

This class mapping between an SQL DATE to Java Date.

DbTimestampType

 

DoubleType

It can be used to mapping between SQL DOUBLE to Java Double.

EmbeddedComponentType

 

EntityType

It communicates an entity class.

FloatType

It links SQL FLOAT to Java Float.

ForeignKeyDirection

This class shows directionality of the foreign key constraint.

IdentifierBagType

 

ImmutableType

This is a superclass of the nullable immutable type.

IntegerType

This class links between the SQL INT to Java Integer.

ListType

 

LocaleType

It links into an SQL VARCHAR and a Java Locale.

LongType

This class links into an SQL BIGINT and a Java Long.

ManyToOneType

It associates many-to-one entity.

MapType

 

MetaType

 

MutableType

This is a superclass of mutable nullable types.

NullableType

This is a supperclass of single-column nullable types.

OneToOneType

It associates one-to-one entity.

OrderedMapType

 

OrderedSetType

 

PrimitiveType

This is the superclass of primitive or primitive wrappers types.

SerializableType

This class maps an SQL VARBINARY to a serializable Java object.

SetType

 

ShortType

It communicates between an SQL SMALLINT and Java Short.

SortedMapType

 

SortedSetType

 

SpacialOneToOneType

 

StringType

It communicates between an SQL VARCHAR and Java String.

TextType

This class links between an SQL CLOB and Java String.

TimestampType

This class mapping between an SQL TIMESTAMP and Java java.util.Date or java.sql.Timestamp.

TimeType

It maps an SQL TIME to  Java java.util.Date or java.sql.Time.

TimeZoneType

It communicates an SQL  VARCHAR to Java java.util.TimeZone.

TrueFalseType

This class maps an SQL CHAR to a Java Boolean.

TypeFactory

This class used internally and holds an instance of Type.

WrapperBinaryType

 

YesNoType

It maps between an SQL CHAR to Java Boolean.

Exceptions and Descriptions:

SerializationException

This exception occurs when the property could not be serialized or deserialized.