Top Banner
Introduction to Java Hibernate Developing enterprise applications involves a lot of efforts to store the business objects in the database. Usually,70% of the efforts to develop enterprise applications are writing the code to maintain database connections and save the entities to database. Most of the enterprise applications are developed using Object Oriented techniques. The business logic inside the application flows in the form of objects instead of textual messages as it used to be in the days of structural programming where we had set of variable to perform operations or indicate the state of an entity. Today,Object Oriented technologies are used to solve the complex problems and maintain the business flow. Only saving the objects to the database is a stage where the objects are transformed back to text and stored to the database. To understand this problem,consider the following code snippets. This is typically how the connection is obtained in Java language. 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: private void saveUser(User user) throws SQLException { PreparedStatement pstmt = connection.prepareStatement("insert into users Hibernate 3.0 Tutorial << Java Tutorial Home Next: Introduction to Hibernate >>
114
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Hibernate(2)

Introduction to Java Hibernate

Developing enterprise applications involves a lot of efforts to store the business objects in the database. Usually,70% of the efforts to develop enterprise applications are writing the code to maintain database connections and save the entities to database. Most of the enterprise applications are developed using Object Oriented techniques. The business logic inside the application flows in the form of objects instead of textual messages as it used to be in the days of structural programming where we had set of variable to perform operations or indicate the state of an entity. Today,Object Oriented technologies are used to solve the complex problems and maintain the business flow. Only saving the objects to the database is a stage where the objects are transformed back to text and stored to the database. To understand this problem,consider the following code snippets.

This is typically how the connection is obtained in Java language.

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:

private void saveUser(User user) throws SQLException{    PreparedStatement pstmt = connection.prepareStatement("insert into users values(?,?,?)");    pstmt.setInt(1,user.getId());    pstmt.setString(2,user.getName());    pstmt.setString(3,user.getEmail());    pstmt.setString(4,user.getAddress());    pstmt.execute();

}

The problem with this code is that this is scattered everywhere in the application which affects the

Hibernate 3.0 Tutorial

  << Java Tutorial Home Next: Introduction to Hibernate >>

Page 2: Hibernate(2)

maintainability of the application. There are many problems with this approach like:

Code is scattered at different un-manageable places.

If your design changes after developing the application,it will be too expensive to identify the places where changes are required.

Difficult to identify and fix the bugs

Managing the database connections is a difficult task since the SQL code is scattered,so are the database connections.

Managing the transactions is a complex task.

Due to these problems,bug fixing is an accepted stage of an application development process which makes the application too expensive even after the successful completion of development cycle.

It is highly needed to have a mechanism to isolate the database persistent code and write it so efficiently that when there is a change in the database design,it can be easily implemented with the belief that there is no un-identified place which may show a bug later.

Benefits of Relational Database Systems:

searching and sorting is fastWork with large amounts of dataWork with groups of dataJoining, aggregatingSharing across multiple users and multiple locationsConcurrency (Transactions)

Hibernate 3.0 Tutorial

Page 3: Hibernate(2)

Support for multiple applicationsConsistent IntegrityConstraints at different levelsTransaction isolation

Issues with Relational Database systems:

Database Modeling does not support polymorphismBusiness logic in the application server could be duplicated in the database as stored proceduresDoes not make use of real world objectsExtra code required to map the Java objects to database objects.

Hibernate is an open source object/relational mapping tool for Java that lets you develop persistent classes and persistent logic without caring how to handle the data. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types),but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. Hibernate's goal is to relieve the developer from 95% of common data persistence related programming tasks.

Hibernate makes it far easier to build robust,high-performance database applications with Java. You only need to write a simple POJO (Plain Old Java Object),create an XML mapping file that describes relationship between the database and the class attributes and call few Hibernate APIs to load/store the persistent objects.

Hibernate 3.0 Tutorial

Page 4: Hibernate(2)

The Object/Relational Mapping Problem

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.

To understand the scenario,consider a web application that collects users personal information and stores them to the database. Also there could be a page that displays all the saved users. When implementing this kind of solution,  we may store the data by getting the request parameters and simply putting it into SQL insert statements. Similarly when displaying,we can select the desired record from the database,and display them on dynamic web page by iterating through the result set. But wait...does it sound good to have persistent related code scattered everywhere on the web page?

Hibernate 3.0 Tutorial

  << Prev: Introduction to Hibernate Next: JDBC >>

Page 5: Hibernate(2)

What if we need to modify the design of our database after we have developed few pages? Or even if we want to replace our low-cost development database with an enterprise-class production database that have entirely different SQL syntax? Do we need to change the SQL queries everywhere in our code?

To overcome this problem,we may want to develop JavaBeans representing the entities in the database. We can develop a Persistence Manager that can operate on the given JavaBean and perform several persistent operations like fetch,store,update,search etc. so that we don't need to write persistence related code in our core area of application. Advantage of using this technique is that we can pass on this simple JavaBean to any of the different layers of the application like a web layer,an EJB layer or any other layer we may have in our application.

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 framework that can take the object to relation mapping and provide persistence facilities on the given JavaBeans,we can use it for different applications and different databases. So,if anyone want to configure the application on a database that was not known at the time of writing the framework,he can simply write a mapping file and the application will start working on that environment.

Thanks to the open source community! we don't need to write such frameworks anymore. We have Hibernate which allows Object/Relation mapping and provides persistence to the abject with the help of simple APIs where we can specify the operations and the operands (JavaBeans).

Hibernate 3.0 Tutorial

Page 6: Hibernate(2)

JDBC

Java Database Connectivity (JDBC) is a set of APIs to connect to the database in a standard way. Since Hibernate provides Object/Relation mapping,it must communicate to the database of your choice. And that cannot happen without the use of a vendor dependent component that understands the target database and the underlying protocol. Usually the database vendors provide set of 'connectors' to connect with their database from external applications with different set of technologies / languages. JDBC driver is widely accepted connector that provides a fairly standard implementation of the JDBC specification. The point of discussion of JDBC here is,that you should know the basics of JDBC and how to use it with Hibernate.

Database connection can be provided by the Hibernate framework or by a JNDI Data source. A third method,user-provided JDBC connections,is also available,but it's rarely used. Typically,in standalone applications,we configure the JDBC connection properties in hibernte.cfg.xml file. In case of applications deployed in an application server,we may choose to use a container-managed data source,or provide a self-managed connection that we might already be using throughout the application. Hibernate itself does not impose a restriction to open or configure a separate connection for the Hibernate use only and keep other configurations to be used by rest of the application.

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.

The Hibernate Alternative

As discussed above,Hibernate provides data storage and retrieval by direct mapping of Object and Relation without letting the application developer worry about the persistence logic. There are few alternatives to Hibernate.

Hibernate 3.0 Tutorial

  << Prev: The Object/Relational Mapping Problem

Next: The Hibernate Alternative >>

  << Prev: JDBC Next: Hibernate Architecture and API

>>

Page 7: Hibernate(2)

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.

There are many other Object/Relation mapping products available like OJB (ObJectRelationalBridge),Torque,Castor,Cayenne,TJDO etc. For more details see http://java-source.net/open-source/persistence

Hibernate Architecture and API

Hibernate is written in Java and is highly configurable through two types of configuration files. The first type of configuration file is named hibernate.cfg.xml. On startup,Hibernate consults this XML file for its operating properties,such as database connection string and password,database dialect,and mapping files locations. Hibernate searches for this file on the classpath. The second type of configuration file is a mapping description file (file extension *.hbm) that instructs Hibernate how to map data between a specific Java class and one or more database tables. Normally in a single application,you would have one hibernate.cfg.xml file,and multiple .hbm files depending upon the business entities you would like to persist.

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

Hibernate 3.0 Tutorial

  << Prev: The Hibernate Alternative Next: Setting Up Hibernate >>

Page 8: Hibernate(2)

database Selecting appropriate SQL Dialect for the database. Creating individual mapping descriptor files for each persistable Java

classes

Here are some commonly used classes of Hibernate.

1.5.1 SessionFactory (org.hibernate.SessionFactory)

SessionFactory is a thread safe (immutable) cache of compiled mappings for a single database. Usually an application has a single SessionFactory. Threads servicing client requests obtain Sessions from the factory. The behavior of a SessionFactory is controlled by properties supplied at configuration time.

1.5.2 Session (org.hibernate.Session)

A session is a connected object representing a conversation between the application and the database. It wraps a JDBC connection and can be used to maintain the transactions. It also holds a cache of persistent objects,used when navigating the objects or looking up objects by identifier.

1.5.3 Transaction (org.hibernate.Transaction)

Transactions are used to denote an atomic unit of work that can be committed (saved) or rolled back together. A transaction can be started by calling session.beginTransaction() which actually uses the transaction mechanism of underlying JDBC connection,JTA or CORBA.A Session might span several Transactions in some cases.

A complete list of Hibernate APIs can be found at http://www.hibernate.org/hib_docs/v3/api/.

Hibernate 3.0 Tutorial

Page 9: Hibernate(2)

Registration Case Study

To demonstrate the different steps involved in a Hibernate application,We will develop a console based application that can add,update,delete or search a user in the database. As discussed previously,we can use Oracle or MySQL database for storing the user information.

We’ll use a single table ‘users’ to store the user information with the following fields:

COLUMN NAME

DATA TYPE CONSTRAINTS

USER_ID NUMBER PRIMARY KEY

FIRST_NAME TEXT NONE

LAST_NAME TEXT NONE

Hibernate 3.0 Tutorial

  << Prev: Setting up Hibernate - Add the Hibernate libraries

Next: Creating the Hibernate Configuration >>

Page 10: Hibernate(2)

AGE NUMBER NONE

EMAIL TEXTNONE

Create this table in the database. The syntax for the oracle is given below.

CREATE TABLE USERS(    USER_ID NUMBER PRIMARY KEY,    FIRST_NAME VARCHAR(20),    LAST_NAME VARCHAR(20),    AGE NUMBER,    EMAIL VARCHAR(40));

If you are using MySQL database,you can create the table using following syntax.

CREATE TABLE USERS(    USER_ID NUMERIC PRIMARY KEY,    FIRST_NAME CHAR(20),    LAST_NAME CHAR(20),    AGE NUMERIC,    EMAIL CHAR(40));

Creating the Hibernate Configuration

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

Hibernate 3.0 Tutorial

  << Prev: Registration Case Study Next: Writing the first Java File >>

Page 11: Hibernate(2)

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.

<?xml version='1.0' encoding='utf-8'?>    <!DOCTYPE hibernate-configuration PUBLIC    "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">    <hibernate-configuration>      <session-factory>        <property name="connection.url">          jdbc:oracle:thin:@localhost:1521:XE        </property>        <property name="connection.driver_class">          oracle.jdbc.driver.OracleDriver        </property>        <property name="connection.username">          SYSTEM        </property>        <property name="connection.password">          manager        </property>        <!-- Set AutoCommit to true -->        <property name="connection.autocommit">          true        </property>        <!-- SQL Dialect to use. Dialects are database specific -->        <property name="dialect">          org.hibernate.dialect.OracleDialect        </property>        <!-- Mapping files -->        <mapping resource="com/visualbuilder/hibernate/User.hbm.xml" />      </session-factory>    </hibernate-configuration>

Hibernate 3.0 Tutorial

Page 12: Hibernate(2)

As you can see,the session factory configuration is set of few properties required for a database connection. connection.url is the JDBC URL required to connect to the database. connection.driver_class is the JDBC Driver class which we normally use in Class.forName while establishing a connection to the database. connection.username and connection.password are the database user name and password respectively. connection.autocommit sets the Autocommit property of the underlying connection. We have set it to true so that we don't need to commit the transactions ourselves unless we want to do it intentionally.

This configuration is for an Oracle database at my machine. If you are unaware of how to build a URL for an Oracle database,note that the you need to replace XE with an appropriate SID of your Oracle database,localhost with the IP address of the machine where Oracle is running if not on local machine,and 1521 with the port. In most cases,you will only change the SID and rest of the parameters will remain the same.

If you are using MySQL,you should put the appropriate URL,Driver class name,user name,password and the Dialect name. The Dialect for MySQL is org.hibernate.dialect.MySQLDialect. Driver class for the MySQL is com.mysql.jdbc.Driver and the URL for MySQL is jdbc:mysql://<server>:<port>/<database-name>. The default port for MySQL is 3306.

The next important step is to add the JDBC driver jar file to the project libraries just like we added the struts libraries. For oracle,it is ojdbc14.zip or ojdbc14.jar and can be found under Oracle installation/jdbc/lib. For example,if Oracle XE is installed in C:\oraclexe,the ojdbc14.jar can be found on the following path. C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib. You can also download it from http://www.minq.se/products/dbvis/drivers.html freely.You can download the MySQL JDBC driver freely from http://dev.mysql.com/downloads/connector/j/5.0.htmll

Writing the first Java File

Hibernate 3.0 Tutorial

  << Prev: Creating the Hibernate Configuration

Next: Writing the mapping file >>

Page 13: Hibernate(2)

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  *  */

public class User {    private long userId = 0 ;    private String firstName = "";    private String lastName = "";    private int age = 0;    private String email = "";        public int getAge() {      return age;    }    public void setAge(int age) {      this.age = age;    }    public String getEmail() {      return email;    }    public void setEmail(String email) {      this.email = email;    }    public String getFirstName() {      return firstName;    }    public void setFirstName(String firstName) {      this.firstName = firstName;    }    public String getLastName() {      return lastName;    }    public void setLastName(String lastName) {      this.lastName = lastName;    }    public long getUserId() {      return userId;    }

Hibernate 3.0 Tutorial

Page 14: Hibernate(2)

    public void setUserId(long userId) {      this.userId = userId;    }  } 

Writing the mapping file

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>        <class name="com.visualbuilder.hibernate.User" table="USERS" >          <id name="userId" type="java.lang.Long" column="user_id" >                <generator class="increment" />          </id>          <property name="firstName" type="java.lang.String" column="first_name" length="20" />          <property name="lastName" type="java.lang.String" column="last_name" length="20" />          <property name="age" type="java.lang.Integer" column="age" length="-1" />          <property name="email" type="java.lang.String" column="email" length="40" />      </class>    </hibernate-mapping> 

Hibernate 3.0 Tutorial

  << Prev: Writing the first Java File Next: Writing the Business Component

>>

Page 15: Hibernate(2)

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.

<?xml version='1.0' encoding='utf-8'?>  <!DOCTYPE hibernate-configuration PUBLIC     "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  <hibernate-configuration>     <session-factory>           <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>        <property name="connection.username">SYSTEM</property>        <property name="connection.password">manager</property>

        <!-- Set AutoCommit to true -->        <property name="connection.autocommit">true</property>

        <!-- SQL Dialect to use. Dialects are database specific -->        <property name="dialect">net.sf.hibernate.dialect.OracleDialect</property>            <!-- Mapping files -->      <mapping resource="com/visualbuilder/hibernate/User.hbm.xml" />        </session-factory>  </hibernate-configuration>

Hibernate 3.0 Tutorial

Page 16: Hibernate(2)

Writing the Business Component

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

 Before writing the business component,we need to understand a hibernate 'session'. As discussed in section 1.5,a hibernate session is an instance of org.hibernate.Session and is obtained by calling openSession() of SessionFactory. Every database operation begins and ends with a Session. For example,we can beginTransaction(),save(),update() or delete() an object with the help of a 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

*/

public class UserManager {

private Session session = null;

public UserManager(Session session)

{

Hibernate 3.0 Tutorial

  << Prev: Writing the mapping file Next: Writing the Test Client >>

Page 17: Hibernate(2)

if(session == null)

throw new RuntimeException("Invalid session object. Cannot instantiate the UserManager");

this.session = session;

}

public void saveUser(User user)

{

session.save(user);

}

public void updateUser(User user)

{

session.update(user);

}

public void deleteUser(User user)

{

session.delete(user);

}

}

Writing the Test Client

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.*;

Hibernate 3.0 Tutorial

  << Prev: Writing the Business Component

Next: Managing Associations >>

Page 18: Hibernate(2)

import org.hibernate.cfg.Configuration;

import com.visualbuilder.hibernate.*;

public class TestClient {

/*

* This method builds a default user to check if the Hiernate configuration is working or not

*/

public User buildUser()

{

User user = new User();

user.setFirstName("John");

user.setLastName("Elison");

user.setAge(21);

user.setEmail("[email protected]");

return user;

}

/*

* This method gets the default SessionFactory configured in hibernate.cfg.xml and opens a session

*/

public Session openSession()

{

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Session session =sessionFactory.openSession();

return session;

}

public User testSaveUser(UserManager manager)

{

User user = buildUser();

Hibernate 3.0 Tutorial

Page 19: Hibernate(2)

manager.saveUser(user);

System.out.println("User saved with ID = " user.getUserId());

return user;

}

public void testUpdateUser(UserManager manager,User user)

{

user.setFirstName("Andrew");

manager.updateUser(user);

System.out.println("User updated with ID = " user.getUserId());

}

public void testDeleteUser(UserManager manager,User user)

{

manager.deleteUser(user);

System.out.println("User deleted with ID = " user.getUserId());

}

public static void main(String[] args)

{

TestClient client = new TestClient();

Session session = client.openSession();

UserManager manager = new UserManager(session);

User user = client.testSaveUser(manager);

client.testUpdateUser(manager,user);

client.testDeleteUser(manager,user);

session.flush();

}

}

Hibernate 3.0 Tutorial

Page 20: Hibernate(2)

Managing Associations

Association is a relationship of one class to another class known as 'relationships' in database terminology. Usually the database design involves the master detail tables to represent the relationship of one entity to another. Struts provides a mechanism to manage one-to-many and many-to-many relationships. Before moving forward,let's create the necessary database tables to show associations.

Let's create a table phone_numbers to represent phone numbers of a user. Following script can be used to create the table in Oracle.

CREATE TABLE PHONE_NUMBERS(    USER_ID NUMBER REFERENCES USERS(USER_ID),    NUMBER_TYPE VARCHAR(50),    PHONE NUMBER,    PRIMARY KEY(USER_ID,NUMBER_TYPE));

The same table can be created in MySQL using the script given below.

CREATE TABLE PHONE_NUMBERS(    USER_ID NUMERIC NOT NULL REFERENCES USERS(USER_ID),    NUMBER_TYPE CHAR(50) NOT NULL,    PHONE NUMERIC,    PRIMARY KEY(USER_ID,NUMBER_TYPE));

We have two tables in the database: USERS and the PHONE_NUMBERS with one to many relationship such that one User many contain 0 or more phone numbers. Create a class PhoneNumber and create its mapping file following the steps to create User class. The code for the PhoneNumber class is shown below.

package com.visualbuilder.hibernate;

import java.io.Serializable;

Hibernate 3.0 Tutorial

  << Prev: Writing the Test Client Next: Finding by primary key >>

Page 21: Hibernate(2)

/**

* PhoneNumber

* @author VisualBuilder

*/

public class PhoneNumber implements Serializable

{

private long userId = 0;

private String numberType = "home";

private long phone = 0;

public String getNumberType() {

return numberType;

}

public void setNumberType(String numberType) {

this.numberType = numberType;

}

public long getPhone() {

return phone;

}

public void setPhone(long phone) {

this.phone = phone;

}

public long getUserId() {

return userId;

}

Hibernate 3.0 Tutorial

Page 22: Hibernate(2)

public void setUserId(long userId) {

this.userId = userId;

}

}

Note that we have made the PhoneNumber class Serializeable. This is because we need a composite key in this class,and Hibernate requires tat the class that represents the composite key must be Serializeable. The mapping file 'PhoneNumber.hbm.xml' contains following text.

<?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="com.visualbuilder.hibernate.PhoneNumber" table="PHONE_NUMBERS" >      <composite-id>            <key-property column="USER_ID"  name="userId" type="java.lang.Long" />            <key-property column="NUMBER_TYPE"  name="numberType" type="java.lang.String"/>        </composite-id>         <property name="phone" type="java.lang.Long">            <column name="PHONE" precision="22" scale="0" />        </property>   </class></hibernate-mapping> 

Add the mapping resource for PhoneNumber in hibernate.cfg.xml file. To do this,locate the line <mapping resource="com/visualbuilder/hibernate/User.hbm.xml" /> in the hibernate.cfg.xml file and add the following line just after this line.

<mapping resource="com/visualbuilder/hibernate/PhoneNumber.hbm.xml" />

Hibernate 3.0 Tutorial

Page 23: Hibernate(2)

We want to write few lines of code so that when we select a user,we automatically get all the phone numbers associated with this user. To do this,add a method 'getPhoneNumbers' that returns a list of users in class User and 'setPhoneNumbers' that takes a List as argument. The complete listing of class User after adding these two methods is shown below.

package com.visualbuilder.hibernate;

/**

* @author VisualBuilder

*

*/

public class User {

private long userId = 0;

private String firstName = "";

private String lastName = "";

private int age = 0;

private String email = "";

private java.util.Set phoneNumbers = new java.util.HashSet();

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getEmail() {

return email;

}

Hibernate 3.0 Tutorial

Page 24: Hibernate(2)

public void setEmail(String email) {

this.email = email;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public long getUserId() {

return userId;

}

public void setUserId(long userId) {

this.userId = userId;

}

public java.util.Set getPhoneNumbers() {

return phoneNumbers;

}

public void setPhoneNumbers(java.util.Set phoneNumbers) {

if(phoneNumbers != null)

Hibernate 3.0 Tutorial

Page 25: Hibernate(2)

this.phoneNumbers = phoneNumbers;

}

}

The phoneNumbers HashTable will be used to store all phone numbers associated with this User. The new changes are highlighted in gray. We have added the methods for getting and setting the phone umbers,we need to add the mapping for the phone numbers now. Add the following block in User.hbm.xml before the </class> tag.

<set name="phoneNumbers" cascade="all">

<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.

  PhoneNumber ph = new PhoneNumber();  ph.setUserId(user.getUserId());  ph.setNumberType("Office");  ph.setPhone(934757);  user.getPhoneNumbers().add(ph);   ph = new PhoneNumber();  ph.setUserId(user.getUserId());  ph.setNumberType("Home");  ph.setPhone(934757);  user.getPhoneNumbers().add(ph);

Hibernate 3.0 Tutorial

Page 26: Hibernate(2)

  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.

So far,we have dealt with one to many association,we can configure the Hibernate for one to one and many to many associations. For more details on how to make Hibernate configuration for other kind of associations,see http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#tutorial-associations

 Finding by primary key

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.

Add the following method in UserManager class.

public User getUser(long userId)

{

User user = (User)session.get(User.class, new Long(userId));

return user;

}

Hibernate 3.0 Tutorial

  << Prev: Managing Associations Next: Hibernate Query Language (HQL)

>>

Page 27: Hibernate(2)

This is the whole logic of finding a user by primary key. Let's test this code by adding the following method in TestClient.

public void testFindByPk(UserManager manager)

{

User user = manager.getUser(1);//Find the user with id=1

if(user == null) {

System.out.println("No user found with ID=1");

}else {

System.out.println("User found with ID=" user.getUserId() "\n"

"\tName=" user.getLastName() "\n"

"\tEmail=" user.getEmail()

"");

java.util.Iterator numbers = user.getPhoneNumbers().iterator();

while(numbers.hasNext()) {

PhoneNumber ph = (PhoneNumber)numbers.next();

System.out.println("\t\tNumber Type:" ph.getNumberType() "\n"

"\t\tPhone Number:" ph.getPhone());

}

}

}

Add the call to this method in main. To do this,add the following line in main.client.testFindByPk(manager);

Hibernate 3.0 Tutorial

Page 28: Hibernate(2)

Replace the user id 1 by some reasonable user id that exists in the database and there are few phone numbers added against that user id. You will see the following output.

User found with ID=1

Name=Elison

[email protected]

Number Type:Office

Phone Number:934757

Number Type:Home

Phone Number:934757

Hibernate Query Language (HQL)

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.

update users set age=31 where user_id in(5,8,9,11,13,14);

 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.

Hibernate 3.0 Tutorial

  << Prev: Finding by primary key Next: Using native SQL >>

Page 29: Hibernate(2)

public java.util.List getUsersByAge(int minAage)

{

org.hibernate.Query q = session.createQuery("from User u where u.age >= :minAge");

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.

Let's write a piece of ode to test this functionality. Add the following method in TestClient.

public void testFindByAge(UserManager manager)

{

java.util.Iterator users = manager.getUsersByAge(30).iterator();

while(users.hasNext())

{

User user = (User)users.next();

System.out.println("User found with ID=" user.getUserId() "\n"

"\tName=" user.getLastName() "\n"

"\tEmail=" user.getEmail()

"");

Hibernate 3.0 Tutorial

Page 30: Hibernate(2)

java.util.Iterator numbers = user.getPhoneNumbers().iterator();

while(numbers.hasNext()) {

PhoneNumber phone = (PhoneNumber)numbers.next();

System.out.println("\t\tNumber Type:" phone.getNumberType() "\n"

"\t\tPhone Number:" phone.getPhone());

}

}

}

Add the call to this method in main. To do this,add the following line in main.client.testFindByAge(manager);

Run the program and see that all the users we modified above are displayed with respective phone numbers.

Following points should be kept in mind when working with HQL.

Queries are case insensitive,except the Java class and attribute names. Hence SELECT and select are the same,but User and user are not.

If the class or package does not find a place in imports,then the objects have to be called with the package name. For example,if com.visualbuilder.hibernate.User is not imported,then the query would be "from com.visualbuilder.hibernate.User" and so on.

Using native SQL

Hibernate 3.0 Tutorial

Page 31: Hibernate(2)

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.

public User getUserById(long userId){    org.hibernate.SQLQuery query = session.createSQLQuery(""        "SELECT u.user_id as {u.userId},u.first_name as {u.firstName},u.last_name as {u.lastName},u.age as {u.age},u.email as {u.email} "        "FROM USERS {u} WHERE  {u}.user_id=" userId "");    query.addEntity("u",User.class);    java.util.List l = query.list();    java.util.Iterator users = l.iterator();    User user = null;    if(users.hasNext())         user = (User)users.next();    return user;}

In the above code,the result type is registered using query.addEntity("u",User.class) so that Hibernate knows how to translate the ResultSet obtained by executing the query. Also note that the aliases in the query are placed in braces and use the same prefix "u" as registered in query.addEntity(...). This way Hibernate knows  how to set attributes of the generated object. Also this way we can eliminate the confusion of attributes when more than one tables are used in query and both of them contain the same column name. query.list() actually executes the query and returns the ResulSet in the form of list of objects. We knew that this query is going to return only one object,so we returned only the first object if available.

Hibernate 3.0 Tutorial

  << Prev: Hibernate Query Language (HQL)

Next: Using Criteria Queries >>

Page 32: Hibernate(2)

Let's test this code by adding the following method in the TestClient.

public void testFindByNativeSQL(UserManager manager)

{

User user = manager.getUserById(2);

System.out.println("User found using native sql with ID=" user.getUserId() "\n"

"\tName=" user.getLastName() "\n"

"\tEmail=" user.getEmail()

"");

java.util.Iterator numbers = user.getPhoneNumbers().iterator();

while(numbers.hasNext()) {

PhoneNumber phone = (PhoneNumber)numbers.next();

System.out.println("\t\tNumber Type:" phone.getNumberType() "\n"

"\t\tPhone Number:" phone.getPhone());

}

}

Add the call to this method in main. To do this,add the following line in main.client.testFindByNativeSQL(manager);

Be sure to pass a valid user id to this method that exists in the database with few valid phone numbers. This code will result in the following output.

User found using native sql with ID=2

Name=Elison

[email protected]

Hibernate 3.0 Tutorial

Page 33: Hibernate(2)

Number Type:Office

Phone Number:934757

Number Type:Home

Phone Number:934757

For more details on using native SQL in Hibernate,see Hibernate documentation.

Using Criteria Queries

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.

public java.util.List getUserByCriteria(Long[] items)

{

org.hibernate.Criteria criteria = session.createCriteria(User.class);

criteria.add(org.hibernate.criterion.Restrictions.in("userId", items));

return criteria.list();

}

Hibernate 3.0 Tutorial

  << Prev: Using native SQL Next: Using Ant to run the project >>

Page 34: Hibernate(2)

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.

public void testFindByCriteria(UserManager manager)

{

java.util.Iterator users = manager.getUserByCriteria(new Long[]{new Long(1),new Long(2)}).iterator();

while(users.hasNext())

{

User user = (User)users.next();

System.out.println("User found with ID="+user.getUserId()+"\n" +

"\tName="+user.getLastName()+"\n" +

"\tEmail="+user.getEmail() +

"");

java.util.Iterator numbers = user.getPhoneNumbers().iterator();

while(numbers.hasNext()) {

PhoneNumber phone = (PhoneNumber)numbers.next();

System.out.println("\t\tNumber Type:"+phone.getNumberType()+"\n" +

"\t\tPhone Number:"+phone.getPhone());

}

}

Hibernate 3.0 Tutorial

Page 35: Hibernate(2)

}

Add the call to this method in main. To do this,add the following line in main.client.testFindByCriteria(manager);

We passed the two user ids to the function. So we should get the two users (if we have in the database with these user id's) with appropriate phone number entries if they exist in the database. Here is what gets displayed under my environment. You should adjust the appropriate user id's to get the results.

User found with ID=1

Name=Elison

[email protected]

Number Type:Office

Phone Number:934757

Number Type:Home

Phone Number:934757

User found with ID=2

Name=Elison

[email protected]

Number Type:Home

Phone Number:934757

Number Type:Office

Phone Number:934757

Using Ant to run the project

Hibernate 3.0 Tutorial

Page 36: Hibernate(2)

In previous sections,we have learnt the widely used components of Hibernate. Our development environment was eclipse and a set of Hibernate libraries. Usually ant is used to build and run the Hibernate applications. In this section,we will configure our project to use ant  and build without any help of eclipse even from command line.

To start with ant:

Download and install the latest available version Apache Ant from http://ant.apache.org

Set environment variable JAVA_HOME to point to the available JDK location like d:\java\j2sdk1.4.2_04

Set environment variable ANT_HOME to point to the ant installation directory like d:\java\apache-ant-1.6.2

Add %ANT_HOME%\bin to your PATH environment variable so that the ant binaries are accessible.

Our ant installation is ready. Let's configure our project to use ant.

Create a directory lib at the root of our project and place the libraries required by our project in this folder. The libraries include all the Hibernate jar files we added in eclipse project libraries and the JDBC driver. See the directory structure below to find where to place the libraries.

Hibernate 3.0 Tutorial

  << Prev: Using Criteria Queries Next: Using Middlegen to generate source

>>

Page 37: Hibernate(2)

Create an xml file at the root of the project. i.e. where the src and lib resides; and add the following text in this file.

<?xml version="1.0"?>

<project name="hibernate-tutorial" default="run" basedir=".">

<!-- set global properties for this build -->

<property name="srcdir" value="src"/>

<property name="jardir" value="jars"/>

<property name="builddir" value="build"/>

Hibernate 3.0 Tutorial

Page 38: Hibernate(2)

<property name="libdir" value="lib"/>

<property name="package" value="com/visualbuilder/hibernate"/>

<path id="cp">

<fileset dir="${libdir}">

<include name="*.jar"/>

<include name="hibernate/*.jar"/>

<include name="hibernate/lib/*.jar"/>

</fileset>

</path>

<target name="init">

<mkdir dir="${builddir}"/>

<mkdir dir="${jardir}"/>

</target>

<target name="clean">

<delete quiet="true" dir="${builddir}"/>

<delete quiet="true" dir="${jardir}"/>

</target>

<target name="compile" depends="init">

<javac srcdir="${srcdir}" destdir="${builddir}" classpathref="cp">

<include name="${package}/*.java"/>

Hibernate 3.0 Tutorial

Page 39: Hibernate(2)

<include name="${package}/client/*.java"/>

</javac>

</target>

<target name="jar" depends="compile">

<jar destfile="${jardir}/app.jar">

<fileset dir="${builddir}">

<include name="${package}/**/*.class"/>

</fileset>

<fileset dir="${srcdir}">

<include name="${package}/*.hbm.xml"/>

<include name="*.cfg.xml"/>

</fileset>

</jar>

</target>

<target name="run" depends="jar">

<java classname="com.visualbuilder.hibernate.client.TestClient" classpathref="cp">

<classpath>

<pathelement location="${jardir}/app.jar" />

</classpath>

</java>

</target>

Hibernate 3.0 Tutorial

Page 40: Hibernate(2)

</project>

This is the main build script that can be used to automatically build the source,copy the configuration files(*.hbm.xml and *.cfg.xml),build the jar file and execute the program. Open the command prompt,change your current directory to the project root,and issue the following command: antThe out put of this command is shown below:

E:\eclipseprojects\hibernate-tutorial>ant

Buildfile: build.xml

init:

[mkdir] Created dir: E:\eclipseprojects\hibernate-tutorial\build

[mkdir] Created dir: E:\eclipseprojects\hibernate-tutorial\jars

compile:

[javac] Compiling 4 source files to E:\eclipseprojects\hibernate-tutorial\build

jar:

[jar] Building jar: E:\eclipseprojects\hibernate-tutorial\jars\app.jar

run:

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

[java] log4j:WARN Please initialize the log4j system properly.

[java] User found with ID=14

[java] Name=Elison

[java] [email protected]

[java] Number Type:Home

Hibernate 3.0 Tutorial

Page 41: Hibernate(2)

[java] Phone Number:934757

[java] Number Type:Office

[java] Phone Number:934757

[java] User found with ID=17

[java] Name=Elison

[java] [email protected]

[java] Number Type:Home

[java] Phone Number:934757

[java] Number Type:Office

[java] Phone Number:934757

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

Hibernate 3.0 Tutorial

Page 42: Hibernate(2)

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 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.  

Filters for working with temporal (historical), regional or permissioned data.   

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.   

Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free.   

Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the clustered environments.  

Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.  

Automatic Key Generation: Hibernate supports the automatic generation of primary key for your.  

 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. 

EJB3-style persistence operations: EJB3 defines the create() and merge() operations, which are slightly different to Hibernate's saveOrUpdate() and saveOrUpdateCopy() operations. Hibernate3 will support all four operations as

Hibernate 3.0 Tutorial

Page 43: Hibernate(2)

methods of the Session interface.  

Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.  

The EJB3 draft specification support for POJO persistence and annotations.

Detailed features are available at http://www.hibernate.org/About/RoadMap.

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:

Connection ManagementHibernate Connection management service provide efficient management of the

Hibernate 3.0 Tutorial

Page 44: Hibernate(2)

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.  

Object relational mapping:Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.

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 HibernateIn 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:

Hibernate 3.0 Tutorial

Page 45: Hibernate(2)

<?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:

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

Hibernate 3.0 Tutorial

Page 46: Hibernate(2)

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

Writing First Persistence ClassHibernate 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;

Hibernate 3.0 Tutorial

Page 47: Hibernate(2)

  }

  /**   * @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 tableThe 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>

Hibernate 3.0 Tutorial

Page 48: Hibernate(2)

 </class></hibernate-mapping>

Setting Up MySQL DatabaseIn 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 exampleNow 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("[email protected]");        session.save(contact);        System.out.println("Done");    }catch(Exception e){

Hibernate 3.0 Tutorial

Page 49: Hibernate(2)

      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.

Hibernate 3.0 Tutorial

Page 50: Hibernate(2)

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

Hibernate 3.0 Tutorial

Page 51: Hibernate(2)

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

Hibernate 3.0 Tutorial

Page 52: Hibernate(2)

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.

Hibernate 3.0 Tutorial

Page 53: Hibernate(2)

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.

Hibernate 3.0 Tutorial

Page 54: Hibernate(2)

 

 

 

 

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> elementThe first or root element of hibernate mapping document is <hibernate-mapping> element. Between the <hibernate-mapping> tag class element(s) are present.   

2.  <class> elementThe <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>

Hibernate 3.0 Tutorial

Page 55: Hibernate(2)

mappings are possible.  

3.  <id> elementThe <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> elementThe <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.       

5. <property> elementThe 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

Hibernate 3.0 Tutorial

Page 56: Hibernate(2)

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 hibernate:

GeneratorDescription

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.

identityIt 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.

seqhiloThe 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.

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

nativeIt 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

Hibernate 3.0 Tutorial

Page 57: Hibernate(2)

no <generator> element is specified.

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

foreignuses 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 {

Hibernate 3.0 Tutorial

Page 58: Hibernate(2)

  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.xmlAdd 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 outHere is the code of our client program to test the application.

/**

Hibernate 3.0 Tutorial

Page 59: Hibernate(2)

 * @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 Importsimport 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

                          

Hibernate 3.0 Tutorial

Page 60: Hibernate(2)

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());    }  }

}

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.

Hibernate 3.0 Tutorial

Page 61: Hibernate(2)

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

Hibernate 3.0 Tutorial

Page 62: Hibernate(2)

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?

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.   

Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any.   

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.  

Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

 

Understanding HQL SyntaxAny Hibernate Query Language may consist of following elements:

Clauses Aggregate functions Subqueries

Clauses in the HQL are:

Hibernate 3.0 Tutorial

Page 63: Hibernate(2)

from select where order by group by

Aggregate functions are:

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

SubqueriesSubqueries 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;

Hibernate 3.0 Tutorial

Page 64: Hibernate(2)

/*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

Hibernate 3.0 Tutorial

Page 65: Hibernate(2)

13 Motorcycle Insurance 900 2004-06-06 00:00:00

14 Motorcycle Insurance 780 2005-03-03 00:00:00

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;  }  /**

Hibernate 3.0 Tutorial

Page 66: Hibernate(2)

   * @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 fileAdd 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>

Hibernate 3.0 Tutorial

Page 67: Hibernate(2)

<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>

HQL from clause Example

                          

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

Hibernate 3.0 Tutorial

Page 68: Hibernate(2)

 * * 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{    }

  }  

}

 

To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:

Hibernate Select Clause

                          

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

Hibernate 3.0 Tutorial

Page 69: Hibernate(2)

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{    }  }

}

To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:

Hibernate 3.0 Tutorial

Page 70: Hibernate(2)

Hibernate: select insurance0_.ID as col_0_0_, insurance0_.insurance_name as col_1_0_, insurance0_.invested_amount as col_2_0_, insurance0_.investement_date as col_3_0_ from insurance insurance0_

ID: 1

Name: Car Insurance

Amount: 1000

ID: 2

Name: Life Insurance

Amount: 100

ID: 3

Name: Life Insurance

Amount: 500

ID: 4

Name: Car Insurance

Amount: 2500

ID: 5

Name: Dental Insurance

Amount: 500

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 )

Hibernate 3.0 Tutorial

Page 71: Hibernate(2)

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());    }  }

}

Download this code.

Hibernate 3.0 Tutorial

Page 72: Hibernate(2)

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

2Life Insurance

250000000-00-00 00:00:00

1 Givan Dhara 20000 2007-07-30 17:29:05

3Life Insurance

  5002005-10-15 00:00:00

4Car Insurance 

  25002005-01-01 00:00:00

5Dental Insurance

5002004-01-01 00:00:00

Hibernate 3.0 Tutorial

Page 73: Hibernate(2)

6 Life Insurance

9002003-01-01 00:00:00

7 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 3.0 Tutorial

Page 74: Hibernate(2)

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

Average of Invested Amount: 7342.8571

Hibernate Min() Function (Aggregate Functions)

                          

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. 

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

min( [ distinct | all ] object.property)

The Min() function aggregates the minimum value of the given column. 

Table Name: insurance

ID

insurance_name

invested_amount

investement_date

2Life Insurance

250000000-00-00 00:00:00

1 Givan Dhara 20000 2007-07-30 17:29:05

3Life Insurance

  5002005-10-15 00:00:00

4Car Insurance 

  25002005-01-01 00:00:00

5Dental Insurance

5002004-01-01 00:00:00

6 Life Insurance

9002003-01-01 00:00:00

Hibernate 3.0 Tutorial

Page 75: Hibernate(2)

7 Travel Insurance

  2000 2005-02-02 00:00:00

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

package roseindia.tutorial.hibernate;

import java.util.List;

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

public class HibernateHQLMinFunction {

  /**   * @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());    }  }

}

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 min(insurance0_.invested_amount) as col_0_0_ from insurance insurance0_

Min Invested Amount: 500

Hibernate 3.0 Tutorial

Page 76: Hibernate(2)

HQL Where Clause Example

                          

Where Clause is used to limit the results returned from database. It can be used with aliases and if the aliases are not present in the Query, the properties can be referred by name. For example:

from Insurance where lngInsuranceId='1'

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("*******************************");

Hibernate 3.0 Tutorial

Page 77: Hibernate(2)

     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{    }      }

}

To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console: *******************************

Query using Hibernate Query Language

Hibernate: select insurance0_.ID as col_0_0_ from insurance insurance0_ where (insurance0_.ID='1')

ID: 1

Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?

Name: Car Insurance

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

Where Clause With Select Clause

Hibernate: select insurance0_.ID as col_0_0_, insurance0_.insurance_name as col_1_0_, insurance0_.invested_amount as col_2_0_, insurance0_.investement_date as col_3_0_ from insurance insurance0_ where (insurance0_.ID='1')

ID: 1

Name: Car Insurance

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

Hibernate 3.0 Tutorial

Page 78: Hibernate(2)

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:

 

 

 

 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();

Hibernate 3.0 Tutorial

Page 79: Hibernate(2)

    } 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:

Hibernate: select sum(insurance0_.invested_amount) as col_0_0_, insurance0_.insurance_name as col_1_0_ from insurance insurance0_ group by insurance0_.insurance_name

Invested Amount: 3500

Insurance Name: Car Insurance

Invested Amount: 500

Insurance Name: Dental Insurance

Invested Amount: 1550

Insurance Name: Home Insurance

Invested Amount: 1500

Insurance Name: Life Insurance

Invested Amount: 1600

Insurance Name: Medical Insurance

Invested Amount: 1680

Insurance Name: Motorcycle Insurance

Invested Amount: 2600

Insurance Name: Travel Insurance

HQL Order By Example

                          

Hibernate 3.0 Tutorial

Page 80: Hibernate(2)

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:

 

 

 

 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 Order by Clause Example *   */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 {    }  }

}

To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:

Hibernate 3.0 Tutorial

Page 81: Hibernate(2)

Hibernate Criteria Query Example

                          

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 {    }    

Hibernate 3.0 Tutorial

Page 82: Hibernate(2)

  }

}

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

addThe 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

createCriteriaThis 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

Hibernate 3.0 Tutorial

Page 83: Hibernate(2)

query.

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

setMaxResultsThis 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.

Hibernate 3.0 Tutorial

Page 84: Hibernate(2)

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).

Hibernate 3.0 Tutorial

Page 85: Hibernate(2)

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.*;import java.util.*;/** * @author vinod Kumar *  * http://www.roseindia.net Hibernate Criteria Query Example *   */public class HibernateCriteriaQueryBetweenTwoInteger {  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 {    }      }

}

Download this code:

Output:

Hibernate 3.0 Tutorial

Page 86: Hibernate(2)

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

log4j:WARN Please initialize the log4j system properly.

Hibernate: select this_.ID as ID0_0_, this_.insurance_name as insurance2_0_0_, this_.invested_amount as invested3_0_0_, this_.investement_date as investem4_0_0_ from insurance this_ where this_.invested_amount between ? and ? limit ?

ID: 1

Name: Car Insurance

Amount: 1000

ID: 4

Name: Car Insurance

Amount: 2500

ID: 7

Name: Travel Insurance

Amount: 2000

Hibernate Native SQL Example

                          

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:

Hibernate 3.0 Tutorial

Page 87: Hibernate(2)

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*/

Hibernate 3.0 Tutorial

Page 88: Hibernate(2)

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());}

When you run the program through it should display the following result:

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

log4j:WARN Please initialize the log4j system properly.

Hibernate: select stddev(ins.invested_amount) as stdErr, avg(ins.invested_amount) as mean from insurance ins

mean amount: 592.1584

stdErr amount: 923.5714

Hibernate: select ins.ID as ID0_, ins.insurance_name as insurance2_2_0_, ins.invested_amount as invested3_2_0_, ins.investement_date as investem4_2_0_ from insurance ins

ID: 1

Name: Car Insurance

ID: 2

Hibernate 3.0 Tutorial

Page 89: Hibernate(2)

Name: Life Insurance

ID: 3

Name: Life Insurance

ID: 4

Name: Car Insurance

......

.......

Hibernate 3.0 Tutorial