+ All Categories
Home > Documents > Hibernate

Hibernate

Date post: 29-Oct-2014
Category:
Upload: nagendra-venkat-thati
View: 49 times
Download: 7 times
Share this document with a friend
Popular Tags:
215
1) Introduction While working with Hibernate web applications we will face so many problems in its performance due to database traffic. That to when the database traffic is very heavy . Actually hibernate is well used just because of its high performance only. So some techniques are necessary to maintain its performance. Caching is the best technique to solve this problem. In this article we will discuss about, how we can improve the performance of Hibernate web applications using caching. The performance of Hibernate web applications is improved using caching by optimizing the database applications. The cache actually stores the data already loaded from the database, so that the traffic between our application and the database will be reduced when the application want to access that data again. Maximum the application will works with the data in the cache only. Whenever some another data is needed, the database will be accessed. Because the time needed to access the database is more when compared with the time needed to access the cache. So obviously the access time and traffic will be reduced between the application and the database. Here the cache stores only the data related to current running application. In order to do that, the cache must be cleared time to time whenever the applications are changing. Here are the contents. Introduction. o First-level cache. o Second-level cache. Cache Implementations. o EHCache. o OSCache. o SwarmCache. o JBoss TreeCache. Caching Stringategies. o Read-only. o Read-Write. o Nonstriict read-write. o Transactional. Configuration. <cache> element. Caching the queries. Custom Cache. o Configuration. o Implementation :: ExampleCustomCache.
Transcript
Page 1: Hibernate

1) Introduction

While working with Hibernate web applications we will face so many problems in its performance due to database traffic. That to when the database traffic is very heavy . Actually hibernate is well used just because of its high performance only. So some techniques are necessary to maintain its performance. Caching is the best technique to solve this problem. In this article we will discuss about, how we can improve the performance of Hibernate web applications using caching.

The performance of Hibernate web applications is improved using caching by optimizing the database applications. The cache actually stores the data already loaded from the database, so that the traffic between our application and the database will be reduced when the application want to access that data again. Maximum the application will works with the data in the cache only. Whenever some another data is needed, the database will be accessed. Because the time needed to access the database is more when compared with the time needed to access the cache. So obviously the access time and traffic will be reduced between the application and the database. Here the cache stores only the data related to current running application. In order to do that, the cache must be cleared time to time whenever the applications are changing. Here are the contents.

Introduction. o First-level cache.o Second-level cache.

Cache Implementations. o EHCache.o OSCache.o SwarmCache.o JBoss TreeCache.

Caching Stringategies. o Read-only.o Read-Write.o Nonstriict read-write.o Transactional.

Configuration. <cache> element. Caching the queries. Custom Cache.

o Configuration.o Implementation :: ExampleCustomCache.

Something about Caching. o Performance.o About Caching.

Conclusion.

Hibernate uses two different caches for objects: first-level cache and second-level cache..

Page 2: Hibernate

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will available to the entire application, don’t bounds to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also. Later we will discuss about it.

2) Cache Implementations

Hibernate supports four open-source cache implementations named EHCache (Easy Hibernate Cache), OSCache (Open Symphony Cache), Swarm Cache, and JBoss Tree Cache. Each cache has different performance, memory use, and configuration possibilities.

2.1) 2.1 EHCache (Easy Hibernate Cache) (org.hibernate.cache.EhCacheProvider)

It is fast. lightweight. Easy-to-use. Supports read-only and read/write caching. Supports memory-based and disk-based caching. Does not support clustering.

2.2)OSCache (Open Symphony Cache) (org.hibernate.cache.OSCacheProvider)

It is a powerful . flexible package supports read-only and read/write caching. Supports memory- based and disk-based caching. Provides basic support for clustering via either JavaGroups or JMS.

2.3)SwarmCache (org.hibernate.cache.SwarmCacheProvider)

is a cluster-based caching. supports read-only or nonstrict read/write caching . appropriate for applications those have more read operations than write

Page 3: Hibernate

operations.

2.4)JBoss TreeCache (org.hibernate.cache.TreeCacheProvider)

is a powerful replicated and transactional cache. useful when we need a true transaction-capable caching architecture .

3) Caching Stringategies

Important thing to remembered while studying this one is none of the cache providers support all of the cache concurrency strategies.

3.1) Read-only

Useful for data that is read frequently but never updated. It is Simple . Best performer among the all.

Advantage if this one is, It is safe for using in a cluster. Here is an example for using the read-only cache strategy.

<class name="abc.mutable " mutable="true "><cache usage="read-only"/>....</class>

3.2) Read-Write

Used when our data needs to be updated. It’s having more overhead than read-only caches. When Session.close() or Session.disconnect() is called the transaction should be

completed in an environment where JTA is no used. It is never used if serializable transaction isolation level is required. In a JTA environment, for obtaining the JTA TransactionManager we must specify

the property hibernate.transaction.manager_lookup_class. To use it in a cluster the cache implementation must support locking.

Here is an example for using the read-write cache stringategy.

<class name="abc.xyz" .... ><cache usage="read-write"/>….<set name="yuv" ... ><cache usage="read-write"/>….</set></class>

3.3) Nonstrict read-write

Page 4: Hibernate

Needed if the application needs to update data rarely. we must specify hibernate.transaction.manager_lookup_class to use this in a

JTA environment . The transaction is completed when Session.close() or Session.disconnect() is

called In other environments (except JTA) .

Here is an example for using the nonstrict read-write cache stringategy.

<class name="abc.xyz" .... ><cache usage=" nonstringict-read-write"/>….</class>

3.4) Transactional

It supports only transactional cache providers such as JBoss TreeCache. only used in JTA environment.

4) Configuration

For configuring cache the hibernate.cfg.xml file is used. A typical configuration file is shown below.

<hibernate-configuration>

<session-factory>...<property name="hibernate.cache.provider_class">

org.hibernate.cache.EHCacheProvider</property>...

</session-factory></hibernate-configuration>

The name in <property> tag must be hibernate.cache.provider_class for activating second-level cache. We can use hibernate.cache.use_second_level_cache property, which allows you to activate and deactivate the second-level cache. By default, the second-level cache is activated and uses the EHCache.

5) <cache> element

The <cache> element of a class has the following form:

<cache usage=" caching stringategy" region="RegionName" include="all | non-lazy"/>

usage (mandatory) specifies the caching stringategy: transactional, read-write,

Page 5: Hibernate

nonstringict-read-write or read-only. region (optional) specifies the name of the second level cache region . include (optional) non-lazy specifies that properties of the entity mapped with

lazy="true" may not be cached when attribute-level lazy fetching is enabled.

The <cache> element of a class is also called as the collection mapping.

6) Caching the queries

Until now we saw only caching the transactions. Now we are going to study about the caching the queries.Suppose some queries are running frequently with same set of parameters, those queries can be cached. We have to set hibernate.cache.use_query_cache to true by calling Query.setCacheable(true) for enabling the query cache. Actually updates in the queries occur very often. So, for query caching, two cache regions are necessary.

For storing the results.( cache identifier values and results of value type only). For storing the most recent updates.

Query cache always used second-level cache only. Queries wont cached by default. Here is an example implementation of query cache.

List xyz = abc.createQuery("Query") .setEntity("…",….) .setMaxResults(some integer) .setCacheable(true) .setCacheRegion("region name") .list();

We can cache the exact results of a query by setting the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true as follows:

<property name="hibernate.cache.use_query_cache">true</property>

Then, we can use the setCacheable() method on any query we wish to cache.

7) Custom Cache

To understand the relation between cache and the application the cache implementation must generate statistics of cache usage.

7.1) Custom Cache Configuration

In the hibernate.properties file set the property hibernate.cache.provider_class = examples.customCache.customCacheProvider.

Page 6: Hibernate

7.2) Implementation :: ExampleCustomCache

Here is the implementation of ExampleCustomCache. Here it uses Hashtable for storing the cache statistics.

package examples.ExampleCustomCache;

import net.sf.hibernate.cache;import java.util;import org.apache.commons.logging;

public class ExampleCustomCache implements Cache{ public Log log = LogFactory.getLog(ExapleCustomCache.class); public Map table = new Hashtable(100);int hits, misses, newhits, newmisses, locks, unlocks, remhits, remmisses, clears, destroys; public void statCount(StringBuffer input, String string1, int value) { input.append(string1 + " " + value); }

public String lStats() { StringBuffer res = new StringBuffer();

statCount(res, "hits", hits); statCount(res, "misses", misses); statCount(res, "new hits", newhits); statCount(res, "new misses", newmisses); statCount(res, "locks", lock); statCount(res, "unlocks", unlock); statCount(res, "rem hits ", remhits); statCount(res, "rem misses", remmisses); statCount(res, "clear", clears); statCount(res, "destroy", destroys);

return res.toString(); }

public Object get(Object key) { if (table.get(key) == null) { log.info("get " + key.toString () + " missed"); misses++; } else { log.info("get " + key.toString () + " hit"); hits++; }

return table.get(key);

Page 7: Hibernate

}

public void put(Object key, Object value) { log.info("put " + key.toString ()); if (table.containsKey(key)) { newhits++; } else { newmisses++; } table.put(key, value); }

public void remove(Object key) { log.info("remove " + key.toString ()); if (table.containsKey(key)) { remhits++; } else { remmisses++; } table.remove(key); }

public void clear() { log.info("clear"); clears++; table.clear(); }

public void destroy() { log.info("destringoy "); destroys++; }

public void lock(Object key) { log.info("lock " + key.toStringing()); locks++; } public void unlock(Object key) { log.info("unlock " + key.toStringing()); unlocks++; }

Here is the example of Custom Cache.

Page 8: Hibernate

Package examples.ExapleCustomCache;

import java.util;import net.sf.hibernate.cache;

public class ExampleCustomCacheProvider implements CacheProvider{

public Hashtable cacheList = new Hashtable();

public Hashtable getCacheList() { return cacheList; }

public Stringing cacheInfo () { StringingBuffer aa = new StringingBuffer(); Enumeration cList = cacheList.keys();

while (cList.hasMoreElements()) { Stringing cName = cList.nextElement().toStringing(); aa.append(cName); ExapleCustomCache myCache = (ExapleCustomCache)cacheList.get(cName);

aa.append(myCache.lStats()); }

return aa.toStringing(); }

public ExampleCustomCacheProvider() { }

public Cache bCache(String string2, Properties properties) { ExampleCustomCache nC = new ExapleCustomCache(); cacheList.put(string2, nC); return nC; }

}

8) Something about Caching

8.1) Performance

Hibernate provides some metrics for measuring the performance of caching, which are all described in the Statistics interface API, in three categories:

Metrics related to the general Session usage.

Page 9: Hibernate

Metrics related to the entities, collections, queries, and cache as a whole. Detailed metrics related to a particular entity, collection, query or cache

region.

8.2) About Caching

All objects those are passed to methods save(), update() or saveOrUpdate() or those you get from load(), get(), list(), iterate() or scroll() will be saved into cache.

flush() is used to synchronize the object with database and evict() is used to delete it from cache.

contains() used to find whether the object belongs to the cache or not. Session.clear() used to delete all objects from the cache . Suppose the query wants to force a refresh of its query cache region, we should

call Query.setCacheMode(CacheMode.REFRESH).

9) Conclusion

Caching is good one and hibernate found a good way to implement it for improving its performance in web applications especially when more database traffic occurs. If we implement it very correctly, we will get our applications to be running at their maximum capacities. I will cover more about the caching implementations in my coming articles. Try to get full coding guidelines before going to implement this.

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

Page 10: Hibernate

and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.

 

Here is the code:

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

<hibernate-configuration><session-factory>      <property name="hibernate.connection.driver_class">

com.mysql.jdbc.Driver</property>      <property name="hibernate.connection.url">

jdbc:mysql://localhost/hibernatetutorial</property>      <property name="hibernate.connection.username">root</property>      <property

Page 11: Hibernate

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

Page 12: Hibernate

following databases dialect type property:

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;

Page 13: Hibernate

  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;

Page 14: Hibernate

  }

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

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

  /**   * @param string sets the Last Name   */

Page 15: Hibernate

  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

Page 16: Hibernate

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>

Page 17: Hibernate

<property name="lastName"> <column name="LASTNAME"/> </property> <property name="email"> <column name="EMAIL"/> </property> </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:

Page 18: Hibernate

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;

Page 19: Hibernate

    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]");

Page 20: Hibernate

        session.save(contact);        System.out.println("Done");    }catch(Exception e){      System.out.println(e.getMessage());    }finally{      // Actual contact insertion will happen at this step      session.flush();      session.close();

      }      }}

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

Hibernate Update Query

                          

Page 21: Hibernate

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

Page 22: Hibernate

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

Page 23: Hibernate

sfully!");    }    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.

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"

Page 24: Hibernate

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 {

Page 25: Hibernate

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

Page 26: Hibernate

}

Hibernate Query Language

                          

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

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

Page 27: Hibernate

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.

Page 28: Hibernate

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:

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

Page 29: Hibernate

query. Hibernate supports Subqueries if the underlying database supports it.

 

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

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:

Page 30: Hibernate

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

Page 31: Hibernate

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

Page 32: Hibernate

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

Page 33: Hibernate

Hibernate Count Query

                          

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

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

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

sum ( [ distinct | all ] object.property)

avg( [ distinct | all ] object.property)

Page 34: Hibernate

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[] arg

Page 35: Hibernate

s) {    // 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 groupby 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();

Page 36: Hibernate

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

}

Download this code.

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:

Page 37: Hibernate

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

Page 38: Hibernate

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

Page 39: Hibernate

     String SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1'";     Query query = session.createQuery(SQL_QUERY);     for(Iterator it=query.iterate();it.hasNext();){       Insurance insurance=(Insurance)it.next();       System.out.println("ID: " + insurance.getLngInsuranceId());       System.out.println("Name: " + insurance. getInsuranceName());            }     System.out.println("*******************************");     System.out.println("Where Clause With Select Clause");    //Where Clause With Select Clause

Page 40: Hibernate

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

Page 41: Hibernate

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

HQL Group By Clause Example

                          

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

Page 42: Hibernate

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

Page 43: Hibernate

      SessionFactory sessionFactory = new Configuration().configure()          .buildSessionFactory();      session = sessionFactory.openSession();      //Group By Clause Example      String SQL_QUERY = "select sum(insurance.investementAmount),insurance.insuranceName "          + "from Insurance insurance group by insurance.insuranceName"; Query query = session.createQuery(SQL_QUERY); for (Iterator it = query.iterate(); it.hasNext();) { Object[] row = (Object[]) it.next(); System.out.println("Invested Amount: " + row[0]); System.out.println("Insurance Name: " + row[1]);      }      session.close();    } catch (Exception e) {      System.out.println(e.getMessage()

Page 44: Hibernate

);    } finally {    }  }}

HQL Order By Example

                          

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

Page 45: Hibernate

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

Page 46: Hibernate

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

Page 47: Hibernate

  }}

Page 48: Hibernate

.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?

An ORM solution consists of the followig four pieces:

API for performing basic CRUD operations API to express queries refering to classes Facilities to specify metadata Optimization facilities : dirty checking,lazy

associations fetching

3.What are the ORM levels ?

The ORM levels are:

Pure relational (stored procedure.) Light objects mapping (JDBC) Medium object mapping Full object Mapping (composition,inheritance,

polymorphism, persistence by reachability)

4.What is Hibernate?

Page 49: Hibernate

Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

Improved productivityo High-level object-oriented API o Less Java code to write o No SQL to write

Improved performanceo Sophisticated caching o Lazy loading o Eager loading

Improved maintainabilityo A lot less code to write

Improved portabilityo ORM framework generates database-specific

SQL for you

6.What Does Hibernate Simplify?

Page 50: Hibernate

Hibernate simplifies:

Saving and retrieving your domain objects Making database column and table name changes Centralizing pre save and post retrieve logic Complex joins for retrieving related items Schema creation from object model

7.What is the need for Hibernate xml mapping file?

Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

8.What are the most common methods of Hibernate configuration?

Page 51: Hibernate

The most common methods of Hibernate configuration are:

Programmatic configuration XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?

Following are the important tags of hibernate.cfg.xml:

10.What are the Core interfaces are of Hibernate framework?

Page 52: Hibernate

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

Session interface SessionFactory interface Configuration interface Transaction interface Query and Criteria interfaces

11.What role does the Session interface play in Hibernate?

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

Session interface role:

Wraps a JDBC connection Factory for Transaction

Page 53: Hibernate

Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate?

The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?

The general flow of Hibernate communication with RDBMS is :

Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files

Page 54: Hibernate

Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)?

Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?

First we need to write Java domain objects (beans with setter and getter).

Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :

<hibernate-mapping>  <class name="com.test.User"  table="user">   <property  column="USER_NAME" length="255"       name="userName" not-null="true" 

Page 55: Hibernate

type="java.lang.String"/>   <property  column="USER_PASSWORD" length="255" name="userPassword" not-null="true"  type="java.lang.String"/> </class></hibernate-mapping

6.What’s the difference between load() and get()?

load() vs. get() :-

load()  get() 

Only use the load() method if you are sure that the object exists. 

If you are not sure that the object exists, then use one of the get() methods. 

load() method will throw an exception if the unique id is not found in the database. 

get() method will return null if the unique id is not found in the database. 

load() just returns a proxy by default and database

get() will hit the database immediately. 

Page 56: Hibernate

won’t be hit until the proxy is first invoked.  

17.What is the difference between and merge and update ?

Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

18.How do you define sequence generated primary key in hibernate?

Using <generator> tag.Example:-

<id column="USER_ID" name="id" type="java.lang.Long"> <generator class="sequence"> <param name="table">SEQUENCE_NAME</param>  <generator></id>

19.Define cascade and inverse option in one-many mapping?

Page 57: Hibernate

cascade - enable operations to cascade to child entities.cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

20.What do you mean by Named – SQL query?

Named SQL queries are defined in the mapping xml document and called wherever required.Example:

<sql-query name = "empdetails">   <return alias="emp" class="com.test.Employee"/>      SELECT emp.EMP_ID AS {emp.empid},                 emp.EMP_ADDRESS AS {emp.address},                 emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name</sql-query>

Page 58: Hibernate

Invoke Named Query :

List people = session.getNamedQuery("empdetails")

.setString("TomBrady", name)

.setMaxResults(50) .list();

21.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="employee">  <return-property name="empid" column="EMP_ID"/>       

<return-property name="name" column="EMP_NAME"/>        <return-property name="address" column="EMP_ADDRESS"/>    { ? = call selectAllEmployees() } </return></sql-query>

22.Explain Criteria API

Page 59: Hibernate

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.Example :

List employees = session.createCriteria(Employee.class)

       .add(Restrictions.like("name", "a%") )

         .add(Restrictions.like("address", "Boston"))

.addOrder(Order.asc("name") ) .list();

23.Define HibernateTemplate?

org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

24.What are the benefits does HibernateTemplate provide?

Page 60: Hibernate

The benefits of HibernateTemplate are :

HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.

Common functions are simplified to single method calls.

Sessions are automatically closed. Exceptions are automatically caught and converted to

runtime exceptions.

25.How do you switch between relational databases without code changes?

Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

26.If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows: <property name="show_sql">true</property>

27.What are derived properties?

Page 61: Hibernate

The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

28.What is component mapping in Hibernate?

A component is an object saved as a value, not as a reference

A component can be saved directly without needing to declare interfaces or identifier properties

Required to define an empty constructor Shared references not supported

Example:

Page 62: Hibernate

29.What is the difference between sorted and ordered collection in hibernate?

sorted collection vs. order collection :-

sorted collection  order collection 

A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which

Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval. 

Page 63: Hibernate

running Hibernate, after the data being read from database using java comparator. 

If your collection is not large, it will be more efficient way to sort it. 

If your collection is very large, it will be more efficient way to sort it . 

What is the advantage of Hibernate over jdbc?

Hibernate Vs. JDBC :-

JDBC  Hibernate 

With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.  

Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. 

Page 64: Hibernate

With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.  

Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.  

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.  

Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.  

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code

Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is

Page 65: Hibernate

written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. 

change in Database or in any table then the only need to change XML file properties.  

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.  

Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.  

With JDBC, caching is maintained by hand-coding.

Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of

Page 66: Hibernate

query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.  

In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  

Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to

Page 67: Hibernate

database then it does not allow saving it because this user does not have updated data.  

32.What are the Collection types in Hibernate ?

Bag Set List Array Map

33.What are the ways to express joins in HQL?

HQL provides four ways of expressing (inner and outer) joins:-

An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.

34.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities.cascade="all|none|save-update|delete|all-delete-orphan"

Page 68: Hibernate

inverse - mark this collection as the "inverse" end of a bidirectional association.inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

35.What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?

By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.How can a whole class be mapped as immutable?

Page 69: Hibernate

Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed

dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ?

A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to

Page 70: Hibernate

navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

40.What is automatic dirty checking?

Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

41.What is transactional write-behind?

Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

People who read this, also read:-JDBC Interview Questions JSF Tutorial WebSphere Certification JSF Integration with Spring Framework

JDBC Interview Questions

42.What are Callback interfaces?

Page 71: Hibernate

Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

43.What are the types of Hibernate instance states ?

Three types of instance states:

Transient -The instance is not associated with any persistence context

Persistent -The instance is associated with a persistence context

Detached -The instance was associated with a persistence context which has been closed – currently not associated

44.What are the differences between EJB 3.0 & Hibernate

Hibernate Vs EJB 3.0 :-

Hibernate  EJB 3.0 

Session–Cache or collection of loaded objects relating to a single unit of work 

Persistence Context-Set of entities that can be managed by a given EntityManager is

Page 72: Hibernate

defined by a persistence unit 

XDoclet Annotations used to support Attribute Oriented Programming 

Java 5.0 Annotations used to support Attribute Oriented Programming 

Defines HQL for expressing queries to the database 

Defines EJB QL for expressing queries 

Supports Entity Relationships through mapping files and annotations in JavaDoc 

Support Entity Relationships through Java 5.0 annotations 

Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API 

Provides and Entity Manager Interface for managing CRUD operations for an Entity 

Provides callback support through lifecycle, interceptor, and validatable interfaces 

Provides callback support through Entity Listener and Callback methods 

Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships 

Entity Relationships are bidirectional or unidirectional 

Page 73: Hibernate

45.What are the types of inheritance models in Hibernate?

There are three types of inheritance models in Hibernate:

Table per class hierarchy Table per subclass Table per concrete class

Q) What are the most common methods of Hibernate configuration?A) The most common methods of Hibernate configuration are:* Programmatic configuration* XML configuration (hibernate.cfg.xml)

Q) What are the important tags of hibernate.cfg.xml?A) An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.

Page 74: Hibernate

Q) What are the Core interfaces are of Hibernate framework?A) People who read this also read:The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.* Session interface* SessionFactory interface* Configuration interface* Transaction interface* Query and Criteria interfaces

Q) What role does the Session interface play in Hibernate?A) The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();Session interface role:

* Wraps a JDBC connection* Factory for Transaction* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking

Page 75: Hibernate

up objects by identifier

Q) What role does the SessionFactory interface play in Hibernate?A) The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

Q) What is the general flow of Hibernate communication with RDBMS?A) The general flow of Hibernate communication with RDBMS is :* Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files* Create session factory from configuration object* Get one session from this session factory* Create HQL Query* Execute query to get list containing Java objects

Page 76: Hibernate

Q) What is Hibernate Query Language (HQL)?A) Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

Q) How do you map Java Objects with Database tables?A) * First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.* Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :<hibernate-mapping><class name=”com.test.User”  table=”user”><property  column=”USER_NAME” length=”255″name=”userName” not-null=”true”  type=”java.lang.String”/><property  column=”USER_PASSWORD” length=”255″name=”userPassword” not-null=”true”  type=”java.lang.String”/></class></hibernate-mapping>

Page 77: Hibernate

Q) What Does Hibernate Simplify?A) Hibernate simplifies:

* Saving and retrieving your domain objects* Making database column and table name changes* Centralizing pre save and post retrieve logic* Complex joins for retrieving related items* Schema creation from object model

Q) What’s the difference between load() and get()?A) load() vs. get()

load()  :-Only use the load() method if you are sure that the object exists.load() method will throw an exception if the unique id is not found in the database.        load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.

get():-If you are not sure that the object exists, then use one of the get() methods.get() method will return null if the unique id is not found in the database.get() will hit the database immediately.

Q) What is the difference between and merge and update ?

Page 78: Hibernate

A)Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

Q) How do you define sequence generated primary key in hibernate?A) Using <generator> tag.Example:-<id column=”USER_ID” name=”id” type=”java.lang.Long”><generator class=”sequence”><param name=”table”>SEQUENCE_NAME</param><generator></id>

Q) Define cascade and inverse option in one-many mapping?A) cascade – enable operations to cascade to child entities.cascade=”all|none|save-update|delete|all-delete-orphan”inverse – mark this collection as the “inverse” end of a bidirectional association.inverse=”true|false”Essentially “inverse” indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list

Page 79: Hibernate

of children, or ask the children who the parents are?

Q) What does it mean to be inverse?A) It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.

Q) What do you mean by Named – SQL query?A) Named SQL queries are defined in the mapping xml document and called wherever required.Example:<sql-query name = “empdetails”><return alias=”emp” class=”com.test.Employee”/>SELECT emp.EMP_ID AS {emp.empid},emp.EMP_ADDRESS AS {emp.address},emp.EMP_NAME AS {emp.name}FROM Employee EMP WHERE emp.NAME LIKE :name</sql-query>Invoke Named Query :List people = session.getNamedQuery(“empdetails”).setString(“TomBrady”, name).setMaxResults(50).list();

Page 80: Hibernate

Q) How do you invoke Stored Procedures?A) <sql-query name=”selectAllEmployees_SP” callable=”true”><return alias=”emp” class=”employee”><return-property name=”empid” column=”EMP_ID”/><return-property name=”name” column=”EMP_NAME”/><return-property name=”address” column=”EMP_ADDRESS”/>{ ? = call selectAllEmployees() }</return></sql-query>

Q) Explain Criteria APIA) Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like “search” screens where there is a variable number of conditions to be placed upon the result set.Example :List employees = session.createCriteria(Employee.class).add(Restrictions.like(“name”, “a%”) ).add(Restrictions.like(“address”, “Boston”)).addOrder(Order.asc(“name”) ).list();

Q) Define HibernateTemplate?A)

Page 81: Hibernate

org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

Q) What are the benefits does HibernateTemplate provide?A) The benefits of HibernateTemplate are :* HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session.* Common functions are simplified to single method calls.* Sessions are automatically closed.* Exceptions are automatically caught and converted to runtime exceptions.

Q) How do you switch between relational databases without code changes?A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

Q) If you want to see the Hibernate generated SQL statements on console, what should we do?A) In Hibernate configuration file set as follows:<property name=”show_sql”>true</property>

Page 82: Hibernate

Q) What are derived properties?A) The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.People who read this also read:Core Java QuestionsSpring QuestionsSCJP 6.0 CertificationEJB Interview QuestionsServlets Questions

Q) What is component mapping in Hibernate?A) * A component is an object saved as a value, not as a reference* A component can be saved directly without needing to declare interfaces or identifier        properties* Required to define an empty constructor* Shared references not supported

Q) What is the difference between sorted and ordered collection in hibernate?A) sorted collection vs. order collectionsorted collection :-A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM

Page 83: Hibernate

which running Hibernate, after the data being read from database using java comparator.If your collection is not large, it will be more efficient way to sort it.

order collection :-Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.If your collection is very large, it will be more efficient way to sort it .

) What is Hibernate?

Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following object-oriented principles such as association, inheritance, polymorphism, composition, and collections.

2) What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database

Page 84: Hibernate

using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another.

3) What does an ORM solution comprises of?

It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes

Should have a language or an API for specifying queries that refer to the classes and the properties of classes

An ability for specifying mapping metadata It should have a technique for ORM implementation

to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

4) What are the different levels of ORM quality?

There are four levels defined for ORM quality.

i. Pure relationalii. Light object mapping

iii. Medium object mappingiv. Full object mapping

5) What is a pure relational ORM?

Page 85: Hibernate

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

6) What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

7) What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

8) What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special

Page 86: Hibernate

base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

9) What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most important one.

i. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.

ii. Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.

iii. Performance – Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.

iv. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

10) How does hibernate code looks like?

Page 87: Hibernate

Session session = getSessionFactory().openSession();

Transaction tx = session.beginTransaction();

MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");

session.save(mpc);tx.commit();session.close();

.

11) What is a hibernate xml mapping document and how does it look like?

In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes’ map to the columns of the relative tables in database.

<?xml version="1.0"?>

Page 88: Hibernate

<!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping> <class

name="sample.MyPersistanceClass" table="MyPersitaceTable">

<id name="id" column="MyPerId">

<generator class="increment"/> </id> <property name="text"

column="Persistance_message"/> <many-to-one name="nxtPer"

cascade="all" column="NxtPerId"/> </class></hibernate-mapping>

Everything should be included under tag. This is the main tag for an xml mapping document.

12) Show Hibernate overview?

13) What the Core interfaces are of hibernate framework?

Page 89: Hibernate

There are many benefits from these. Out of which the following are the most important one.

i. Session Interface – This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.

ii. SessionFactory Interface – This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.

iii. Configuration Interface – This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.

iv. Transaction Interface – This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.

v. Query and Criteria Interface – This interface allows the user to perform queries and also control the flow of the query execution.

14) What are Callback interfaces?

Page 90: Hibernate

These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but they’re useful for implementing certain kinds of generic functionality.

15) What are Extension interfaces?

When the built-in functionalities provided by hibernate is not sufficient enough, it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. These interfaces are called as Extension interfaces.

16) What are the Extension interfaces that are there in hibernate?

There are many extension interfaces provided by hibernate.

ProxyFactory interface - used to create proxies ConnectionProvider interface – used for JDBC

connection management TransactionFactory interface – Used for transaction

management Transaction interface – Used for transaction

management TransactionManagementLookup interface – Used

in transaction management.

Page 91: Hibernate

Cahce interface – provides caching techniques and strategies

CacheProvider interface – same as Cache interface ClassPersister interface – provides ORM strategies IdentifierGenerator interface – used for primary

key generation Dialect abstract class – provides SQL support

17) What are different environments to configure hibernate?

There are mainly two types of environments in which the configuration of hibernate application differs.

i. Managed environment – In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere.

ii. Non-managed environment – This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment.

18) What is the file extension you use for hibernate mapping file?

The name of the file should be like this : filenam.hbm.xml

Page 92: Hibernate

The filename varies here. The extension of these files should be “.hbm.xml”.

This is just a convention and it’s not mandatory. But this is the best practice to follow this extension.

19) What do you create a SessionFactory?

Configuration cfg = new Configuration();

cfg.addResource("myinstance/MyConfig.hbm.xml");

cfg.setProperties( System.getProperties() );

SessionFactory sessions = cfg.buildSessionFactory();

First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().

20) What is meant by Method chaining?

Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not

Page 93: Hibernate

mandatory to use this format. Look how a SessionFactory is created when we use method chaining.

SessionFactory sessions = new Configuration()

.addResource("myinstance/MyConfig.hbm.xml")

.setProperties( System.getProperties() )

.buildSessionFactory();

21) What does hibernate.properties file consist of?

This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file.

hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB

Page 94: Hibernate

hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransactionFactory

hibernate.transaction.manager_lookup_class = net.sf.hibernate.transaction.JBossTransactionManagerLookup

hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDialect

22) What should SessionFactory be placed so that it can be easily accessed?

As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file.

23) What are POJOs?

POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to

Page 95: Hibernate

that property. Hibernate applications works efficiently with POJOs rather then simple java classes.

24) What is object/relational mapping metadata?

ORM tools require a metadata format for the application to specify the mapping between classes and tables, properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations.

25) What is HQL?

HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL.

26) What are the different types of property and class mappings?

Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>Or<property name="description" type="string">

Page 96: Hibernate

<column name="DESCRIPTION"/></property>

Derived properties

<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>

Typical and most common property mapping

<property name="description" column="DESCRIPTION" type="string"/>

Controlling inserts and updates

<property name="name" column="NAME" type="string" insert="false" update="false"/>

27) What is Attribute Oriented Programming?

XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are

Page 97: Hibernate

used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.

28) What are the different methods of identifying an object?

There are three methods by which an object can be identified.

i. Object identity – Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.

ii. Object equality – Objects are equal if they have the same value, as defined by the equals( ) method. Classes that don’t explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity.

iii. Database identity – Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value.

29) What are the different approaches to represent an inheritance hierarchy?

i. Table per concrete class.ii. Table per class hierarchy.

iii. Table per subclass.

Page 98: Hibernate

30) What are managed associations and hibernate associations?

Associations that are related to container management persistence are called managed associations. These are bi-directional associations. Coming to hibernate associations, these are unidirectional.

Q. How will you configure Hibernate?

Answer:

The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service.

" hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the

Page 99: Hibernate

settings found in the hibernate.properties file.

" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

Q. What is a SessionFactory? Is it a thread-safe object?

Answer:

SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an

Page 100: Hibernate

application code.

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

Q. What is a Session? Can you share a session object between different theads?

Answer:

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

& public class HibernateUtil { &

Page 101: Hibernate

public static final ThreadLocal local = new ThreadLocal();

public static Session currentSession() throws HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); local.set(session); } return session; } }

It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.

Q. What are the benefits of detached objects?

Answer:

Detached objects can be passed across layers all the way up to the presentation layer without having to use any

Page 102: Hibernate

DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Q. What are the pros and cons of detached objects?

Answer:

Pros:

" When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.

Cons

" In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway.

Page 103: Hibernate

" Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.

Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?

Answer

" Hibernate uses the version property, if there is one. " If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. " Write your own strategy with Interceptor.isUnsaved().

Page 104: Hibernate

Q. What is the difference between the session.get() method and the session.load() method?

Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.

Q. What is the difference between the session.update() method and the session.lock() method?

Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

Page 105: Hibernate

Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.

Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?

You can use the session.merge() method call.

Q. What are the general considerations or best practices for defining your Hibernate persistent classes?

1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables.

2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only

Page 106: Hibernate

generates and sets the field when saving the object.

3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.

4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.

5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

Hibernate Setup with an web Application

Follow the steps to setup Hibernate.

Page 107: Hibernate

Step 1. Create folders like below.

testApp          |     ----src     // Java Source Code folder              |     -------------beans //Source Code folder                    |     ----------------Offer.java //Source Code    -------------servlet //Source Code folder                    |     ----------------DBStartUpServlet.java //Source Code    -------------dao //Source Code folder                    |     ----------------HibernateUtil.java //Source Code

----config     // config folder where all the configuration files present              |     -------------hibernate.cfg.xml //Hibernate Config file   -------------Offer.hbm.xml// hibernate mapping with Offer TABLE    -------------log4j.properties// log4j setting    ----WEB-INF //within folder               |     ---------web.xml //file   

Page 108: Hibernate

---------classes //folder   ---------lib //within folder                 |     -------------hibernate3.jar //jar file   -------------antlr-2.7.6rc1.jar //jar file   -------------asm.jar //jar file   -------------asm-attrs.jar //jar file   -------------c3p0-0.9.0.jar //jar file for connection pool   -------------classes12.jar //if you use ORACLE DATABASE jar file   -------------mysql-connector-java-5.0.4-bin.jar //if you use MySQL DATABASE jar file   -------------commons-logging.jar //jar file   -------------commons-validator.jar //jar file   -------------dom4j-1.6.1.jar //jar file   -------------jta.jar //jar file   -------------log4j-1.2.11.jar //jar file   -------------nls_charset12.jar //jar file   

Step 2. Add DBStartUpServlet Entry into the web.xml file

This servlet is only for load configuration files related to Hibernate and create Session Factory on start up . Create Session Factory is very ExpensiveCreate Session Factory is very Expensive so

Page 109: Hibernate

we added one servlet to create on server startup Initialize Connection pool on startup Initialize Connection pool on startup using c3p0.Initialize log4j configuration Initialize log4j configuration on startup.

<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-appPUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><display-name>Hibernate</display-name><description>Hibernate Setup </description><servlet><servlet-name>DBStartUpServlet</servlet-name><servlet-class>servlet.DBStartUpServlet</servlet-class> <load-on-startup>1</load-on-startup>

Page 110: Hibernate

</servlet></web-app>

Step 3. DBStartUpServlet Code

package servlet; public class DBStartUpServlet extends HttpServlet {/** Initialising the Logger */protected static final Logger logger=Logger.getLogger(DBStartUpServlet.class);public void init(ServletConfig config) throws ServletException {System.out.println("\n**** Initializing Hibernate Init Servlet ********** \n");super.init(config);

//This is for local properties.String cfgDir = "D:\\testApp\\config";logger.info("config dir:"+cfgDir);initLogPro(cfgDir);

Page 111: Hibernate

try{HibernateUtil.appHome = cfgDir;HibernateUtil.initMonitor();}catch(Exception e){e.printStackTrace();}

}

/** Handles the requests from http client.* @param request servlet request* @param response servlet response*/protected void service(HttpServletRequest request,HttpServletResponse response)throws ServletException, java.io.IOException {}

private void

Page 112: Hibernate

initLogPro(String path){try{PropertyConfigurator.configure(path+File.separatorChar+"log4j.properties");}catch(Exception ex){System.out.println("Log4J can not be initialized");logger.info("Log4J can not be initialized");

}}

}

Step 4. HibernateUtil.java code

package dao;public class HibernateUtil {public static String appHome = "No";private static SessionFactory sessionFactory;private static final ThreadLocal threadSession =

Page 113: Hibernate

new ThreadLocal();private static final ThreadLocal threadTransaction = new ThreadLocal();

// Create the initial SessionFactory from the default configuration filespublic static void configure(){try {String path_properties = appHome+File.separatorChar+"hibernate.cfg.xml";Configuration configuration = new Configuration();configuration.addFile(path_properties);sessionFactory =configuration.configure().buildSessionFactory();

} catch (Throwable ex) {

throw new ExceptionInInitializerError(ex);}

Page 114: Hibernate

}public static SessionFactory getSessionFactory() {if(sessionFactory==null) configure();return sessionFactory;}

public static Session getSession(){Session s = (Session) threadSession.get();// logger.debug("session"+s);if (s == null) {

s = getSessionFactory().openSession();threadSession.set(s);// logger.debug("session 1 $"+s);}return s;}

}

Page 115: Hibernate

Step 5. hibernate.cfg.xml for hibernate configuration (within config folder)

<?xml version='1.0' encoding='utf-8'?><lt;!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/techfaqdb</property><property name="connection.username">techfaq</property><property name="connection.password">techfaq</property><!-- JDBC connection pool (use the built-in) --><property

Page 116: Hibernate

name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_size">4</property><property name="hibernate.c3p0.timeout">1800</property><property name="hibernate.c3p0.max_statements">50</property><!-- MySQL dialect//different for different Database --><property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout -->

Page 117: Hibernate

<property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><mapping resource="Offer.hbm.xml"/></session-factory></hibernate-configuration>

Step 6. Offer.java bean class.(within beans folder)

package beans;public class Offer {private long offerId;private String offerName;/*** @return Returns the offerId.*/ public long getOfferId() {return offerId;}/*** @param offerId The offerId to set.*/private void setOfferId(long offerId) {this.offerId = offerId;}/** * @return Returns the offerName.

Page 118: Hibernate

*/public String getOfferName() {return offerName;}/*** @param offerName The offerName to set.*/public void setOfferName(String offerName) {this.offerName = offerName;}}

Step 7. Offer.java and OFFER TABLE mapping in Offer.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="beans.Offer" table="OFFER">

Page 119: Hibernate

<id name="offerId" column="offer_id" type="long"><generator class="increment"/> // This generates the primary key</id><property name="offerName" column="offer_name"/></class></hibernate-mapping>

Step 8. OFFER TABLE in your database

create table OFFER ( offer_id number; offer_name varchar );

Then start the server. Your SessionFactory is ready to serve.You can call HibernateUtil.getSession() to get session object and do your coding.

Advantage of Hibernate over JDBC

Advantage are1) Hibernate is data base independent, same code will work for all data bases like ORACLE,MySQL ,SQLServer etc.

Page 120: Hibernate

In case of JDBC query must be data base specific.

2) As Hibernate is set of Objects , you don't need to learn SQL language.You can treat TABLE as a Object . In case of JDBC you need to learn SQL.

3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.In case of JDBC you need to tune your queries.

4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.In case of JDBC you need to implement your java cache .

5) Hibernate supports Query cache and It will provide the statistics about your query and database status.JDBC Not provides any statistics.

Page 121: Hibernate

6) Development fast in case of Hibernate because you don't need to write queries.

7) No need to create any connection pool in case of Hibernate. You can use c3p0.In case of JDBC you need to write your own connection pool.

8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.

9) You can load your objects on start up using lazy=false in case of Hibernate.JDBC Don't have such support.10 ) Hibernate Supports automatic versioning of rows but JDBC Not.

First Hibernate Application

This section describe a simple program to insert record into database and fetch the records Follow the setps

Step 1. create a table name EMPLOYEE in your database

Page 122: Hibernate

// for MySQL create table EMPLOYEE (id bigint(20) ,name varchar);// FOR ORACLEcreate table EMPLOYEE (id number;name varchar);

Step 2. Create Emp.java bean class.

Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table (Emp.java to EMPLOYEE TABLE). We can configure the variables to map to the database column.

public class Emp {private long id;private String name;public long getId() {return id;}private void setId(long id) {this.id = id;}

Page 123: Hibernate

public String getName() {return name;}public void setName(String name) {this.name = name;}}

Step 3. Emp.hbm.xml - This mapps EMPLOYEE TABLE and Emp.java

<?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="Emp" table="EMPLOYEE"><id name="id" column="id" type="long"><generator class="increment"/> // This generates the primary key</id>

Page 124: Hibernate

<property name="name" column="name"/></class></hibernate-mapping>

Step 4. add Emp.hbm.xml into hibernate.cfg.xml

Hibernate provided connection pooling usning c3p0 and transaction management . Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment

<?xml version='1.0' encoding='utf-8'?><lt;!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property

Page 125: Hibernate

name="connection.url">jdbc:mysql://localhost:3306/techfaqdb</property><property name="connection.username">techfaq</property><property name="connection.password">techfaq</property><!-- JDBC connection pool (use the built-in) --><property name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_size">4</property><property name="hibernate.c3p0.timeout">1800</property><property name="hibernate.c3p0.max_statements">50</property><!-- MySQL dialect//different for different Database --><property name="dialect">org.hibernate.dialect.MySQLDialect</property>

Page 126: Hibernate

<!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><mapping resource="Emp.hbm.xml"/></session-factory></hibernate-configuration>

Step 5. Here is the code for Save and Fetch data.

Hibernate Session is the main runtime interface for Hibernate which is used for DataBase operataion. Session has the method like save () , update () , creteQuery() for Data Base operation. You can get session using

Page 127: Hibernate

SessionFactory.openSession() method. 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.

public class TestExample {public static void main(String[] args) {Session session = null;try{ // This step will read hibernate.cfg.xml SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();System.out.println("Inserting Records");Emp emp1 = new Emp(); emp1.setName("Nick");session.save(emp1);Emp emp2 = new Emp(); emp2.setName("Das");session.save(emp2);session.flush(); // insert data into databse

Page 128: Hibernate

System.out.println("Save Done- finish database insert");// Now fetch the Employee dataList empList = session.createQuery("from Emp").list();//empList contains the list of Employeefor(int i=0;i<EMPLIST.SIZE();I++){Emp emp = (Emp)empList.get(i);System.out.println(emp.getName());}// Out put is : Nick Das}catch(Exception e){}finally{session.close();}}}

Hibernate mapping with Database TABLE

Follow the steps to mapp with Database TABLE.

Step 1. create a table name OFFER in your database

Page 129: Hibernate

create table OFFER ( offer_id number; offer_name varchar );

Step 2. Create Offer.java bean class.

package beans;public class Offer {private long offerId;private String offerName;/*** @return Returns the offerId.*/ public long getOfferId() {return offerId;}/*** @param offerId The offerId to set.*/private void setOfferId(long offerId) {this.offerId = offerId;}/** * @return Returns the offerName.*/public String getOfferName() {return offerName;}/*** @param offerName The offerName to set.

Page 130: Hibernate

*/public void setOfferName(String offerName) {this.offerName = offerName;}}

Step 3. Offer.hbm.xml - This mapps OFFER TABLE and Offer.java

<?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="beans.Offer" table="OFFER"><id name="offerId" column="offer_id" type="long"><generator class="increment"/> // This generates the primary key</id><property name="offerName"

Page 131: Hibernate

column="offer_name"/></class></hibernate-mapping>

Step 4. add Offer.hbm.xml into hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?><lt;!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/techfaqdb</property><property name="connection.username">techfaq</property><property name="connection.password">techfaq

Page 132: Hibernate

</property><!-- JDBC connection pool (use the built-in) --><property name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_size">4</property><property name="hibernate.c3p0.timeout">1800</property><property name="hibernate.c3p0.max_statements">50</property><!-- MySQL dialect//different for different Database --><property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property

Page 133: Hibernate

name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><mapping resource="Offer.hbm.xml"/></session-factory></hibernate-configuration>

One to Many : Uni-Directional Relation in Hibernate

There are two table WRITER and STORY. One writer can write multiple stories. So the relation is one-to-many uni-directional.

Step 1. create a table name WRITER and STORY in your database

create table WRITER (ID number, //PRIMARY KEYNAME varchar); create table STORY (

Page 134: Hibernate

ID number,INFO varchar,PARENT_ID number // forign key - relate to ID Coulmn of WRITER. );

Step 2. Mapping writer.hbm.xml- Which maps to WRITER TABLE.

<?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="Writer" table="WRITER"><id name="id" column="ID" type="int" unsaved-value="0"><generator class="increment"/></id><list name="stories" cascade="all"><key column="parent_id"/><one-to-many class="Story"/></list>

Page 135: Hibernate

<property name="name" column="NAME" type="string"/></class></hibernate-mapping>

Step 3. Mapping story.hbm.xml- Which maps to STORY TABLE.

<?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="Story" table="story"><id name="id" column="ID" type="int" unsaved-value="0"><generator class="increment"/></id><property name="info" column="INFO" type="string"/></class></hibernate-mapping>

Step 4. Create Writer.java bean class.

Page 136: Hibernate

public class Writer {private int id;private String name;private List stories;public void setId(int i) {id = i;}public int getId() {return id;}public void setName(String n) {name = n;}public String getName() {return name;}public void setStories(List l) {stories = l;}public List getStories() {return stories;}}

Step 5. Create Story.java bean class.

public class Story {private int id;

Page 137: Hibernate

private String info;public Story(){}public Story(String info) {this.info = info;}public void setId(int i) {id = i;}public int getId() {return id;}public void setInfo(String n) {info = n;}public String getInfo() {return info;}}

Step 6. add writer.hbm.xml and story.hbm.xml into hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?><lt;!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

Page 138: Hibernate

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/techfaqdb</property><property name="connection.username">techfaq</property><property name="connection.password">techfaq</property><!-- JDBC connection pool (use the built-in) --><property name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_size">4</property><property name="hibernate.c3p0.timeout">1800

Page 139: Hibernate

</property><property name="hibernate.c3p0.max_statements">50</property><!-- MySQL dialect//different for different Database --><property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><mapping resource="story.hbm.xml"/><mapping resource="writer.hbm.xml"/>

Page 140: Hibernate

</session-factory></hibernate-configuration>

Here is the code : how to save

Save Example ..Writer wr = new Writer();wr.setName("Das");ArrayList list = new ArrayList();list.add(new Story("Story Name 1"));list.add(new Story("Story Name 2"));wr.setStories(list);Transaction transaction = null;try {transaction = session.beginTransaction();session.save(wr);transaction.commit();} catch (Exception e) { if (transaction != null) {transaction.rollback();throw e;}} finally { session.close();}

Page 141: Hibernate

One to Many Bi-Directional Relation in Hibernate

There are two table WRITER and STORY. One writer can write multiple stories. So the relation is one-to-many . This tutorial describe the bi-directional relation. From WRITER object you can get list of Stories and from story object you can get writer object.

Step 1. create a table name WRITER and STORY in your database

create table WRITER (ID number, //PRIMARY KEYNAME varchar); create table STORY (ID number,INFO varchar,PARENT_ID number // forign key - relate to ID Coulmn of WRITER. );

Step 2. Mapping writer.hbm.xml- Which maps to WRITER TABLE.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping

Page 142: Hibernate

PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="Writer" table="WRITER"><id name="id" column="ID" type="int" unsaved-value="0"><generator class="increment"/></id><list name="stories" cascade="all"><key column="parent_id"/><one-to-many class="Story"/></list><property name="name" column="NAME" type="string"/></class></hibernate-mapping>

Step 3. Mapping story.hbm.xml- Which maps to STORY TABLE.

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC

Page 143: Hibernate

"-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="Story" table="story"><id name="id" column="ID" type="int" unsaved-value="0"><generator class="increment"/></id><property name="info" column="INFO" type="string"/><many-to-one name="writer" column="ID" lazy="false"/></class></hibernate-mapping>

Step 4. Create Writer.java bean class.

public class Writer {private int id;private String name;private List stories;public void setId(int i) {id = i;}public int getId() {

Page 144: Hibernate

return id;}public void setName(String n) {name = n;}public String getName() {return name;}public void setStories(List l) {stories = l;}public List getStories() {return stories;}}

Step 5. Create Story.java bean class.

public class Story {private int id;private String info;private Writer writer; public Story(){}public Story(String info) {this.info = info;}public void setId(int i) {id = i;

Page 145: Hibernate

}public int getId() {return id;}public void setInfo(String n) {info = n;}public String getInfo() {return info;}public void setWriter(Writer writer) {this.writer = writer;}public Writer getWriter() {return writer;}}

Step 6. add writer.hbm.xml and story.hbm.xml into hibernate.cfg.xml

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

Page 146: Hibernate

<hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/techfaqdb</property><property name="connection.username">techfaq</property><property name="connection.password">techfaq</property><!-- JDBC connection pool (use the built-in) --><property name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_size">4</property><property name="hibernate.c3p0.timeout">1800</property><property

Page 147: Hibernate

name="hibernate.c3p0.max_statements">50</property><!-- MySQL dialect//different for different Database --><property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><mapping resource="story.hbm.xml"/><mapping resource="writer.hbm.xml"/></session-factory></hibernate-configuration>

Page 148: Hibernate

Many to Many Relation in Hibernate

There are two table EVENTS and SPEAKERS . One Event can have multiple speakers. And One Speaker can speak in multiple Event. So this is many to many relation. To maintain this relation we have to introduce third TABLE name EVENT_SPEAKERS .

Step 1. create a tables EVENTS , SPEAKERS and EVENT_SPEAKERS in your database

create table EVENTS (event_id number, //PRIMARY KEYevent_name varchar); create table SPEAKERS (speaker_id number, //PRIMARY KEYspeaker_name varchar,); create table EVENT_SPEAKERS (elt number,//primary key event_id number, speaker_id number

Page 149: Hibernate

);

Step 2. event.hbm.xml - Hibenate mapping-Which maps to EVENTS TABLE

<?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="Event" table="events"><id name="id" column="event_id" type="long"><generator class="increment"/></id><property name="name" column="event_name" type="string" length="100"/><set name="speakers" table="event_speakers" cascade="all"><key column="event_id"/><many-to-many class="Speaker"/>

Page 150: Hibernate

</set></class></hibernate-mapping>

Step 3. Mapping speaker.hbm.xml- Which maps to SPEAKERS TABLE.

<?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="Speaker" table="speakers"><id name="id" column="speaker_id" type="long"><generator class="increment"/></id><property name="name" column=" speaker_name" type="string" length="100"/><set name="events" table="event_speakers" cascade="all">

Page 151: Hibernate

<key column="speaker_id"/><many-to-many class="Event"/></set></class></hibernate-mapping>

Step 4. Create Event.java bean class.

public class Event{private long id;private String name;private Set speakers;public void setId(long id) {this.id = id;}public long getId() {return id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public void setSpeakers(Set speakers) {this.speakers = speakers;}public Set getSpeakers() {

Page 152: Hibernate

return speakers;}}

Step 5. Create Speaker.java bean class.

public class Speaker{private long id;private String name;private Set events;public void setId(long id) {this.id = id;}public long getId() {return id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set getEvents() {return this.events;}public void setEvents(Set events) {this.events = events;}

Page 153: Hibernate

}

Step 6. add event.hbm.xml and speaker.hbm.xml into hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?><lt;!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><!-- Database connection settings --><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/techfaqdb</property><property name="connection.username">techfaq</property><property name="connection.password">techfaq</property>

Page 154: Hibernate

<!-- JDBC connection pool (use the built-in) --><property name="hibernate.c3p0.min_size">1</property> <property name="hibernate.c3p0.max_size">4</property><property name="hibernate.c3p0.timeout">1800</property><property name="hibernate.c3p0.max_statements">50</property><!-- MySQL dialect//different for different Database --><property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!-- Disable the second-level cache --><property name="cache.provider_class">org.hiber

Page 155: Hibernate

nate.cache.NoCacheProvider</property><!-- Echo all executed SQL to stdout --><property name="show_sql">true</property><property name="hbm2ddl.auto">update</property><mapping resource="event.hbm.xml"/><mapping resource="speaker.hbm.xml"/></session-factory></hibernate-configuration>

Here is the code : how to save and fetch data

Event event = new Event();event.setName("Inverse test");event.setSpeakers(new HashSet());event.getSpeakers().add(new Speaker("Ram", event));event.getSpeakers().add(new Speaker("Syam", event));session.save(event); /// Save All the Dataevent = (Event) session.load(Event.class,

Page 156: Hibernate

event.getId());Set speakers = event.getSpeakers();for (Iterator i = speakers.iterator(); i.hasNext();) {Speaker speaker = (Speaker) i.next();System.out.println(speaker.getFirstName());System.out.println(speaker.getId());}

HQL: The Hibernate Query Language The Hibernate Query Language is executed using session.createQuery(). This tutorial includes from clause,Associations and joins, Aggregate functions,The order by clause,The group by clause,Subqueries.

The from clause

from Employee // Employee is class name mapped to EMPLOYEE TABLEorfrom Employee as e orfrom Employee e where e.empId = 3;

Page 157: Hibernate

List empList = session.createQuery("from Employee").list();

Associations and joins

from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1 List empList = session.createQuery("from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1").list();

Aggregate functions

select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from Cat cat ScrollableResults rs = session.createQuery("select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from Cat cat").scroll();if(rs.next()){System.out.println(rs.get(0));System.out.println(rs.get(1));

Page 158: Hibernate

System.out.println(rs.get(2));System.out.println(rs.get(3));}

The order by clause

from Employee e order by e.name desc List empList = session.createQuery("from Employee e order by e.name desc").list();asc or desc indicate ascending or descending order respectively.

The group by clause

select e.dept, sum(e.salary), count(e) Employee e group by cat.dept

Subqueries

from Employee as e where e.name = some ( select name.nickName from Name as name )

Page 159: Hibernate

Criteria Queries The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances.

Criteria : Select * from Employee.

Criteria criemp = session.createCriteria(Employee.class);List emplist = criemp.list();

Restrictions to narrow result set

The class org.hibernate.criterion.Restrictions used to narrow result set.

// SELECT * FROM EMPLOYEE WHERE AGE=24; ----SQL COMMANDcriteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.eq("age", new Integer(24) ) ).list();

Page 160: Hibernate

// Not Equal in hibernate criteria // SELECT * FROM EMPLOYEE WHERE AGE !=24; ----SQL COMMANDcriteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.ne("age", new Integer(24) ) ).list();

Ordering the results

// SELECT * FROM EMPLOYEE WHERE AGE=24 ORDER BY EMP_NAME DESC; ----SQL COMMANDcriteria query for above query is : List empList = session.createCriteria(Employee.class). add( Restrictions.eq("age", new Integer(24) ) ).addOrder( Order.desc("empname") ).list();

Associations

// SELECT e.name FROM EMPLOYEE e , address a where

Page 161: Hibernate

e.address_id=a.address_id and a.country='US'; ----SQL COMMANDcriteria query for above query is : List empList = session.createCriteria(Employee.class).createAlias("address","add"). add( Restrictions.eq("add.country", "US" ) ).list();

Example queries

The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance.

// SELECT * FROM EMPLOYEE e WHERE e.dept='IT'; ----SQL COMMANDcriteria query for above query is : Employee emp = new Employee();cat.setDept('IT');List emplist = session.createCriteria(Employee.class).add( Example.create(emp) ).list();

….

Page 162: Hibernate

Recommended