Professional Documents
Culture Documents
Hibernate
Hibernate
Class.forName(driverClass);
java.sql.Connection connection =
java.sql.DriverManager.getConnection(databaseUrl,databaseUser,databasePassword);
Suppose we have an object of User class,and we need to store this object to the database. Consider
the following function:
The problem with this code is that this is scattered everywhere in the application which affects the
maintainability of the application. There are many problems with this approach like:
In object oriented systems,we represent entities as objects and classes and use
database to persist those objects. Most of the data-driven applications today,are
written using object oriented technologies. The idea of representing entities as set of
classes is to re-use the classes and objects once written.
We have isolated our persistence related code so that whenever there is a change in
the design,or we change the database environment we can change our persistence
code. Or we can have several copies of the Persistence Manager to work with
different databases so that based on some configuration parameter,we can choose the
right Persistence Manager instance. But this is still very difficult as we might ignore
some database specific settings while writing so many Persistence Managers for
different applications.
Here the concept of Object Relational mapping comes. By Object Relational mapping
(O/R mapping) we mean the one-to-one mapping of class attributes with the columns
of a database entity. Mapping includes the name of the attribute versus database
field,the data type,and relation with other entities or classes. So if we write a
Before starting off with the Hibernate,make sure that you have
essential set of JDBC libraries for the database you are going to use
for your application.
• You may choose to use plain SQL queries to store and retrieve data
but that is not an alternate to Hibernate as using plain SQL queries
does not provide maximum of the features provided by Hibernate.
• You can use Enterprise Java Beans. In particular,Entity Beans are
good alternate to Hibernate. But again,you need to see if you really
have the requirements of an EJB container?
• You can use the spring framework (www.springframework.org) to
implement a DAO layer which would centralize as well as minimize any
future need to change persistence implementations.
Hibernate may be used by any Java application that requires moving data between
Java application objects and database tables. Thus,it's very useful in developing two
and three-tier J2EE applications. Integration of Hibernate into your application
involves:
• Installing the Hibernate core and support JAR libraries into your project
• Creating a Hibernate.cfg.xml file to describe how to access your
database
• Selecting appropriate SQL Dialect for the database.
• Creating individual mapping descriptor files for each persistable Java
classes
We’ll use a single table ‘users’ to store the user information with the
following fields:
TEXT NONE
FIRST_NAME
TEXT NONE
LAST_NAME
NUMBER NONE
AGE
Now it is the time to create our Hibernate configuration file. This file will contain the
hibernate session configuration like the database driver,user name and password or a
JNDI data source if you would like to use one,cache provider ad other session
parameters. Also this file contains the entries for Object to Relation mapping that we
will create later. Initially let's create the file with minimum required information and
understand what does that information mean.
Create a new file hibernate.cfg.xml in src folder and add the following contents to
this file.
Let’s start with our first java class. Remember we have a table “users” in the
database. Let’s write a simple bean that represents this table.
package com.visualbuilder.hibernate;
/**
* @author VisualBuilder
*
*/
Mapping files are the heart of O/R mapping tools. These are the files that contain field
to field mapping between the class attributes and the database columns.
Let's write a mapping file for the User class that we want to persist to the database.
<?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>
</hibernate-mapping>
As you can see,we have mapped all of the attributes of the class "User" to the
columns of the table we created previously. Note the "id" attribute which maps the
userId field of class User is defined in a different way than the other properties. The
id tag is used to indicate that this is a primary key,and a <generator> tag is used to
generate the primary key using different techniques. We have used the increment
class,but there are also available different classes to support different kind of key
generation techniques like generating key from a sequence,selecting from database
etc. We can also use a custom key generator class.
Let us now add the mapping file to the Hibernate configuration file hibernate.cfg.xml.
After adding the mapping resource entry,the hibernate.cfg.xml looks like this.
So far,we have written a User class that we want to persist and a mapping file that
describes the relationship of each of the attributes of the class to the database
columns. We have also configured the Hibernate SessionFactory (hibernate.cfg.xml)
to use the User.hbm.xml. Now it is the time to write a business component that can
perform different operations on the User object.
7.1 Session
Our business component will use the Session to perform its business operations.
package com.visualbuilder.hibernate.client;
import org.hibernate.Session;
import com.visualbuilder.hibernate.User;
/**
* UserManager
* @author VisualBuilder
*/
if(session == null)
Let us write a test client that utilizes the different methods of the UserManager we
have just introduced. We will obtain the SessionFactory and open a session and then
call different methods of the UserManager to see if they work or not.
package com.visualbuilder.hibernate.client;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import com.visualbuilder.hibernate.*;
/*
*/
user.setFirstName("John");
user.setLastName("Elison");
user.setAge(21);
user.setEmail("john@visualbuilder.com");
return user;
/*
*/
<key column="USER_ID"/>
<one-to-many class="com.visualbuilder.hibernate.PhoneNumber"
/>
</set>
As you can see,the tags are very simple. The cascade attribute of set tells the Hibernate how to deal
with the child records when a parent is deleted or a child is added.
Now it is the time to test our functionality. Remember the TestClient class where we had few
blocks of code explaining the save,update and delete functionality. For the time being,comment the
call to testDeleteUser and replace the contents of method testUpdateUser with the following
code.
ph = new PhoneNumber();
ph.setUserId(user.getUserId());
ph.setNumberType("Home");
ph.setPhone(934757);
user.getPhoneNumbers().add(ph);
manager.saveUser(user);
System.out.println("User updated with ID = " user.getUserId());
We are adding two phone numbers to the recently saved user objects. Note that we even don't need
to save the PhoneNumber. These are automatically saved as we add them to the User. Query the
database and see how these instances are persisted. Once you see the values in the database,re-
enable the code to delete the User object and see what happens with the child PhoneNumber
objects.
In the previous section,we tested the basic functionality of our hibernate application. With few lines
of code,we were able to perform the basic operations like insert,update and delete on the database
table,and add few children without writing a single SQL query. In enterprise applications,an
efficient search mechanism is highly needed. Hibernate provides a set of different techniques to
search a persisted object. Let us see a simple mechanism to find an Object by primary key without
using a query.
return user;
This is the whole logic of finding a user by primary key. Let's test this code by adding the
following method in TestClient.
if(user == null) {
}else {
"\tEmail=" user.getEmail()
"");
In the previous section,we tried to find a persisted user by user id which was primary key in that
case. What if we want to search a user by user name,age or email and none of these attributes is a
primary key. Hibernate provides a query language similar to the standard SQL to perform
operations on the Hibernate objects. The advantage of using HQL instead of standard SQL is that
SQL varies as different databases are adopted to implement different solutions,but HQL remain the
same as long as you are within the domain of Hibernate; no matter which database you are using.
Let us learn to embed HQL in our example to find the users with age greater than 30. Before doing
this,make sure that you have some of the users over the age of 30. For example,i issued the
following query on my Oracle console to update the age of few users.
Modify this query to include some of the records in your users table.
Let's write the logic to find the users in our business component. Add the following method in
UserManager.
q.setInteger("minAge", minAage);
return q.list();
Note that the query uses "User" which is the object name and not the table name which is "Users".
Similarly the "u.age" is an attribute of the User object and not the column name of the table. So
whatever the name of the table may be,and whatever the presentation of that table or columns at the
database level may be,we will use the same standard syntax while communicating with the
hibernate. Also note the parameter "minAge". The parameters in an HQL query are represented
with ":"(colon) character and can be bound using the index or the parameter name in
org.hibernate.Query.
In previous section,we learnt to use the Hibernate Query Language (HQL) that focused on the
business entities instead of the vendor dependent syntax. This does not mean that we are bound to
use the HQL throughout the Hibernate application if we want to perform some database operations.
You may express a query in SQL,using createSQLQuery() and let Hibernate take care of the
mapping from result sets to objects. Note that you may at any time call session.connection()
and use the JDBC Connection directly. If you chose to use the Hibernate API,you must enclose
SQL aliases in braces.
Let's see how to use the SQL queries by adding the functionality to find a user by user id using
native SQL in our UserManager. Add the following method in UserManager class.
Let's test this code by adding the following method in the TestClient.
So far we have seen how to use HQL and native SQL to perform certain database operations. We
saw that the HQL was much simpler than the native SQL as we had to provide database columns
and the mapping attributes along with mapping classes too to get fully translated java objects in
native SQL. Hibernate provides much simpler API called Criteria Queries if our intention is only to
filter the objects or narrow down the search. In Criteria Queries,we don't need to provide the select
or from clause. Instead,we just need to provide the filtering criteria. For example name like '%a',or
id in (1,2,3) etc. Like HQL,the Criteria API works on java objects instead on database entities as in
case of native SQL.
Let's write a method in UserManager to filter the users that have user id within a set of passed user
id's.
org.hibernate.Criteria criteria =
session.createCriteria(User.class);
criteria.add(org.hibernate.criterion.Restrictions.in("userId",
items));
return criteria.list();
This method returns the users and associated phone numbers that have one of the user id in items
passed as an argument. See how a certain filter criteria is entered using Restrictions class.
Similarly we can use
Restrictions.like,Restrictions.between,Restrictions.isNotNull,Restrictions.isNull
and other methods available in Restrictions class.
Let's write the test code to verify that the filter we provided using Criteria works. Add the
following method in TestClient.
BUILD SUCCESSFUL
So,you can see that the ant did a magic for us by doing all the configuration,including the
necessary libraries and automatically executing the client program for us.
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
• Enhanced Criteria query API: with full support for projection/aggregation and
subselects.
• Runtime performance monitoring: via JMX or local Java API, including a second-
level cache browser.
• Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate
3.0, including mapping editor, interactive query prototyping, schema reverse
engineering tool.
• JDK 1.5 Enhancements: The new JDK has been released as a preview earlier this
year and we expect a slow migration to the new 1.5 platform throughout 2004.
While Hibernate3 still runs perfectly with JDK 1.2, Hibernate3 will make use of
some new JDK features. JSR 175 annotations, for example, are a perfect fit for
Hibernate metadata and we will embrace them aggressively. We will also support
Java generics, which basically boils down to allowing type safe collections.
• The EJB3 draft specification support for POJO persistence and annotations.
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.
• Connection Management
Hibernate Connection management service provide efficient management of the
database connections. Database connection is the most expensive part of
interacting with the database as it requires a lot of resources of open and close the
database connection.
• Transaction management:
Transaction management service provide the ability to the user to execute more
than one database statements at a time.
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.
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.
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
• DB2 - org.hibernate.dialect.DB2Dialect
• HypersonicSQL - org.hibernate.dialect.HSQLDialect
• Informix - org.hibernate.dialect.InformixDialect
• Ingres - org.hibernate.dialect.IngresDialect
• Interbase - org.hibernate.dialect.InterbaseDialect
• Pointbase - org.hibernate.dialect.PointbaseDialect
• PostgreSQL - org.hibernate.dialect.PostgreSQLDialect
• Mckoi SQL - org.hibernate.dialect.MckoiDialect
• Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect
• MySQL - org.hibernate.dialect.MySQLDialect
• Oracle (any version) - org.hibernate.dialect.OracleDialect
• Oracle 9 - org.hibernate.dialect.Oracle9Dialect
• Progress - org.hibernate.dialect.ProgressDialect
• FrontBase - org.hibernate.dialect.FrontbaseDialect
• SAP DB - org.hibernate.dialect.SAPDBDialect
• Sybase - org.hibernate.dialect.SybaseDialect
• Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect
/**
* @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;
}
/**
/**
* @param l Sets the ID
*/
public void setId(long l) {
id = l;
}
<?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.
session.save(contact)
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();
}
}
Click on "Next" button. In the next screen leave the output folder as default
"hibernateexample/bin" .
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.
In this section I showed you how to run the our first Hibernate 3.0 example.
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.
<?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>
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:
• name: The property name used by the persistent class.
• column: The column used to store the primary key value.
• type: The Java data type used.
• unsaved-value: This is the value used to determine if a class has been
made persistent. If the value of the id attribute is null, then it means that
this object has not been persisted.
4. <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.
5. <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.
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.
Generator Description
It generates identifiers of type long, short or int that
are unique only when no other process is inserting data
increment
into the same table. It should not the used in the
clustered environment.
It supports identity columns in DB2, MySQL, MS
identity SQL Server, Sybase and HypersonicSQL. The returned
identifier is of type long, short or int.
The sequence generator uses a sequence in DB2,
PostgreSQL, Oracle, SAP DB, McKoi or a generator
sequence
in Interbase. The returned identifier is of type long,
short or int
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
hilo
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.
The seqhilo generator uses a hi/lo algorithm to
seqhilo efficiently generate identifiers of type long, short or
int, given a named database sequence.
The uuid generator uses a 128-bit UUID algorithm to
generate identifiers of type string, unique within a
uuid
network (the IP address is used). The UUID is encoded
as a string of hexadecimal digits of length 32.
It uses a database-generated GUID string on MS SQL
guid
Server and MySQL.
It picks identity, sequence or hilo depending upon the
native
capabilities of the underlying database.
lets the application to assign an identifier to the object
assigned before save() is called. This is the default strategy if no
<generator> element is specified.
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.
/**
* @author Deepak Kumar
*
* http://www.roseindia.net
* Java Class to map to the database Book table
*/
package roseindia.tutorial.hibernate;
<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).
/**
* @author Deepak Kumar
*
//Hibernate Imports
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
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.
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.
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;
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.
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;
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
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.
• Full support for relational operations: HQL allows representing SQL queries in
the form of objects. Hibernate Query Language uses Classes and properties
instead of tables and columns.
• Return result as Object: The HQL queries return the query result(s) in the form
of object(s), which is easy to use. This elemenates the need of creating the object
and populate the data from result set.
• Easy to Learn: Hibernate Queries are easy to learn and it can be easily
implemented in the applications.
• Support for Advance features: HQL contains many advance features such as
pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian
products. It also supports Projection, Aggregation (max, avg) and grouping,
Ordering, Sub queries and SQL function calls.
• Clauses
• Aggregate functions
• Subqueries
• from
• select
Subqueries
Subqueries are nothing but its a query within another query. Hibernate supports
Subqueries if the underlying database supports it.
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:
Above Sql query will create insurance table and add the following data:
In this lesson we will write the java class and add necessary code in the contact.hbm.xml
file.
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;
<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" />
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:
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 {
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar.
Following out is displayed in the Eclipse console:
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:
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:
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();
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar.
Following out is displayed in the Eclipse console:
ID: 1
Amount: 1000
ID: 2
Amount: 100
ID: 3
Amount: 500
ID: 4
Amount: 2500
ID: 5
Amount: 500
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.
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 static void main(String[] args) {
// TODO Auto-generated method stub
Output:
Total rows: 6
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.
The avg() function aggregates the average value of the given column.
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;
/**
* @Vinod kumar
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Output:
In this section, we will show you, how to use the Min() 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.
The Min() function aggregates the minimum value of the given column.
Here is the java code to retrieve the minimum value of "invested_amount" column from
insurance table:
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @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 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());
}
}
Output:
Where Clause can be used with or without Select Clause. Here the example code:
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 Where Clause Example
* Where Clause With Select 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]);
session.close();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar.
Following out is displayed in the Eclipse console:
*******************************
ID: 1
*******************************
ID: 1
*******************************
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 Group by Clause Example
*
*/
public class HQLGroupByExample {
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();
//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 {
}
}
}
To run the example select Run-> Run As -> Java Application from the menu bar.
Following out is displayed in the Eclipse console:
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:
To run the example select Run-> Run As -> Java Application from the menu bar.
Following out is displayed in the Eclipse console:
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:
creates the sql query and execute against database to retrieve the data.
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.
Method Description
The Add method adds a Criterion to constrain the results to be
add
retrieved.
addOrder Add an Order to the result set.
createAlias Join an association, assigning an alias to the joined entity
This method is used to create a new Criteria, "rooted" at the
createCriteria
associated entity.
This method is used to set a fetch size for the underlying JDBC
setFetchSize
query.
setFirstResult This method is used to set the first result to be retrieved.
This method is used to set a limit upon the number of objects to be
setMaxResults
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:
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.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}
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 :
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
}
session.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}
Output:
Amount: 1000
ID: 4
Amount: 2500
ID: 7
Amount: 2000
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.
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
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();
}
}
}
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());
}
When you run the program through it should display the following result:
ID: 1
ID: 2
ID: 3
ID: 4
......
.......