Saturday, 27 April 2013


 Criteria based queries in Hibernate
The following examples takes you through a series of aggregate functions, where clauses, group by and order by criteria using hibernate.
MAX( ) :
public int getMaxDeptId() {

    int maxId = 0;

    HibernateTemplate ht = new HibernateTemplate(sessionFactory);
    DetachedCriteria criteria = DetachedCriteria

    List result = ht.findByCriteria(criteria);
    maxId = (Integer) result.get(0);

    return maxId;

Min( ):
public int getMinDeptId() {

    int minId = 0;

    HibernateTemplate ht = new HibernateTemplate(sessionFactory);
    DetachedCriteria criteria = DetachedCriteria

    List result = ht.findByCriteria(criteria);

    minId = (Integer) result.get(0);
    return minId;

Restrictions based Query (AND, OR, comparators):
public List getCustomDepartments() {

 ArrayList values = new ArrayList();

 HibernateTemplate ht = new HibernateTemplate(sessionFactory);
 DetachedCriteria criteria = DetachedCriteria

 criteria.add("deptName", values));
 criteria.add(Restrictions.and("deptName", values),
   Restrictions.le("deptId", 3)));


 return ht.findByCriteria(criteria);

public void getDepartmentsInEachYear() {

    HibernateTemplate ht = new HibernateTemplate(sessionFactory);
    DetachedCriteria criteria = DetachedCriteria


    System.out.println(">>>>" + ht.findByCriteria(criteria).size());

Order By:
public List<departments> getDepartments(boolean ascending) {

    HibernateTemplate ht = new HibernateTemplate(sessionFactory);
    DetachedCriteria criteria = DetachedCriteria

    if (!ascending) {
    } else {

    return ht.findByCriteria(criteria);

Introduction :
In this article, we examine the Hibernate Criteria API, a powerful and elegent alternative to HQL well adapted for dynamic search functionalities where complex Hibernate queries have to be generated 'on-the-fly'. 

Multi-criteria search functionalities:
Complex multi-criteria search functionalities are frequently found in web-enabled business applications. Multi-criteria search screens typically have a large number of search criteria, many of which are optional. Well-known general public multi-criteria search functionalities can be found in the 'Advanced Search' screens on sites such as YahooAltaVista, and Lycos.
When are multi-criteria search screens appropriate?
In many public web sites (such as Amazon), complex multi-criteria search functionnalites tend to be less frequent these days, for the very good reason that users generally don't use them (or at least, not efficiently). EBay for example has a powerful multi-criteria search functionality which for which the business case is probably fairly limited. A good key-word and full-text search is usually preferable for sites aimed at the general public.
There are exceptions, though. Travel sites, such as air and train reservation sites, are cases where multi-criteria searches are both necessary and intuitive.
As we have said, business web sites are also another story.
The traditional approach
The traditional approach to implementing a multi-criteria search query with Hibernate involves building an HQL query on-the-fly, based on the search criteria entered by the user.
Here is an example of one such approach :
Map parameters = new HashMap();
 StringBuffer queryBuf = new StringBuffer("from Sale s ");
 boolean firstClause = true;

 if (startDate != null) {
          queryBuf.append(firstClause ? " where " : " and ");
          queryBuf.append(" >= :startDate");
          firstClause = false;
 if (endDate != null) {
          queryBuf.append(firstClause ? " where " : " and ");
          queryBuf.append(" <= :endDate");
          firstClause = false;
 // And so on for all the query criteria...

 String hqlQuery = queryBuf.toString();
 Query query = session.createQuery(hqlQuery);

 // Set query parameter values
 Iterator iter = parameters.keySet().iterator();
 while (iter.hasNext()) {
          String name = (String);
          Object value = map.get(name);
 // Execute the query
 List results = query.list();
This approach is cumbersome and error-prone. It is also risky in a team-development context, as inexperienced developpers will often take dangerous short-cuts using this approach. During code review, I?ve often come across multi-criteria search functions using error-prone String concatenation, direct use of query parameters in the query string, and so on :
if (startDate != null) {
        if (firstClause) {
               query = query + " where ";
        } else {
               query = query + " and ";
   query += " >= '" + startDate + "'";
// And so on...
As we will see, the Hibernate Criteria API provides a safer and cleaner solution to this type of problem.
Using the Hibernate Criteria API
The Hibernate Criteria API provides an elegant way of building on-the-fly dynamic queries on Hibernate-persisted databases. Using this technique, the previous 24-line example can be coded more consicely and more clearly using a mere 8 lines of code :
Criteria criteria = session.createCriteria(Sale.class);
if (startDate != null) {
if (endDate != null) {
List results = criteria.list();
Let's have a look at the use of the Hibernate Criteria API in more detail.
Creating and using the Hibernate Criteria object
A Criteria object is created using the createCriteria() method in the Hibernate session object :
Criteria criteria = session.createCriteria(Sale.class);
Once created, you add Criterion objects (generally obtained from static methods of theExpression class) to build the query. Methods such as setFirstResult()setMaxResults(), andsetCacheable() may be used to customize the query behaviour in the same way as in the Queryinterface. Finally, to execute the query, the list() (or, if appropriate uniqueResult()) method is invoqued :
List sales = session.createCriteria(Sale.class)
                        .addOrder( Order.asc("date") )
The Hibernate Criteria API supports a rich set of comparaison operators.
The standard SQL operators (=, <, ?, >, ? ) are supported respectively by the following methods in the Expression class : eq(), lt(), le(), gt(), ge() :

Note that, as in HQL and unlike in a JDBC-based query, you are free to use business objects as query parameters, without having to use primary and foriegn key references.
The API also provides additional comparaison operators : likebetweeninisNullisNotNull...
          .add(Expression.between("date", startDate, endDate))


In addition, the API provides convenient operators which : eqPropertyltProperty, etc?
Ordering results
In HQL (and SQL), the order by clause allows you to order your query results. Using the QueryAPI, this is done using the addOrder() method and the Order class :
           .add(Expression.between("date", startDate, endDate))
           .addOrder( Order.desc("date") )
           .addOrder( Order.asc("product.number") )
Joining tables
When writing HQL queries, join clauses are often necessary to optimise the query using a "left join fetch" clause, as in the following example (I discuss this type of optimisation in another article.)
from Sale sale
where > :startDate
left join fetch sale.product
When using the criteria API, you can do the same thing using the setFetchMode() function :
Imagine the case of an online shop which sells shirts. Each shirt model comes in a certain number of available sizes. You want a query to find all the shirt models with sizes over 40. InHQL, the query might be the following :
from Shirt shirt
join shirt.availableSizes size
where size.number > 40
Using the Criteria API, you use the createCriteria() to create an inner join between the two tables, as in the following example :
           .add("number", new Integer(40)))
Another way of doing this is to use the createAlias() method, which does not involve creating a new instance of the Criteria class.
           .add("size.number", new Integer(40)))

Note that in both these cases, the availableSizes collection in each Shirt object will not be initialised : it is simply used as part of the search criteria.
When the Hibernate Criteria API is not appropriate
As we can see, the Hibernate Criteria API is without doubt tailor-made for dynamic query generation. It is worth noting however that there are many places where its use is not appropriate, and indeed will create code which is more complex and harder to maintain than using a standard HQL query. If the query to be executed does not involve dynamic construction (that is, the HQL query can be externalised as a named query in the Hibernate mapping files), than the use of the Hibernate Criteria API is probably not appropriate. When possible, externalising static queries presents a number of advantages :
§ Externalised queries can be audited and optimised if necessary by the DBA
§ Named queries stored in the Hibernate mapping files are easier to maintain than queries scattered through the Java code
§ Hibernate Named Queries are easy to cache if necessary
§  Criteria Queries
§  Creating a Criteria instance
§  The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. 

     Criteria crit = sess.createCriteria(Cat.class);
§  crit.setMaxResults(50);
§  List cats = crit.list()
      Narrowing the result set
§  An individual query criterion is an instance of the interface org.hibernate.criterion.Criterion. The classorg.hibernate.criterion.Restrictions defines factory methods for obtaining certain built-in Criterion types.

 List cats = sess.createCriteria(Cat.class)
§      .add("name", "Fritz%") )
§      .add( Restrictions.between("weight", minWeight, maxWeight) )
§      .list();
§  Restrictions can be grouped logically.

  List cats = sess.createCriteria(Cat.class)
§      .add("name", "Fritz%") )
§      .add( Restrictions.or(
§          Restrictions.eq( "age", new Integer(0) ),
§          Restrictions.isNull("age")
§      ) )
§      .list();
§  List cats = sess.createCriteria(Cat.class)
§      .add( "name", new String[] { "Fritz", "Izi", "Pk" } ) )
§      .add( Restrictions.disjunction()
§          .add( Restrictions.isNull("age") )
§          .add( Restrictions.eq("age", new Integer(0) ) )
§          .add( Restrictions.eq("age", new Integer(1) ) )
§          .add( Restrictions.eq("age", new Integer(2) ) )
§      ) )
§      .list();§  There are a range of built-in criterion types (Restrictions subclasses). One of the most useful allows you to specify SQL directly.

List cats = sess.createCriteria(Cat.class)
§      .add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING) )
§      .list();

§  The {alias} placeholder with be replaced by the row alias of the queried entity.
You can also obtain a criterion from a Property instance. You can create a Property by callingProperty.forName(): 

 Property age = Property.forName("age");
§  List cats = sess.createCriteria(Cat.class)
§      .add( Restrictions.disjunction()
§          .add( age.isNull() )
§          .add( age.eq( new Integer(0) ) )
§          .add( age.eq( new Integer(1) ) )
§          .add( age.eq( new Integer(2) ) )
§      ) )
§      .add( Property.forName("name").in( new String[] { "Fritz", "Izi", "Pk" } ) )
§      .list(); 
Ordering the results

§  You can order the results using org.hibernate.criterion.Order.

List cats = sess.createCriteria(Cat.class)
§      .add("name", "F%")
§      .addOrder( Order.asc("name") )
§      .addOrder( Order.desc("age") )
§      .setMaxResults(50)
§      .list();
§  List cats = sess.createCriteria(Cat.class)
§      .add( Property.forName("name").like("F%") )
§      .addOrder( Property.forName("name").asc() )
§      .addOrder( Property.forName("age").desc() )
§      .setMaxResults(50)
§      .list(); 

§  By navigating associations using createCriteria() you can specify constraints upon related entities:
 List cats = sess.createCriteria(Cat.class)
§      .add("name", "F%") )
§      .createCriteria("kittens")
§          .add("name", "F%") )
§      .list();
 §  The second createCriteria() returns a new instance of Criteria that refers to the elements of the kittenscollection.
There is also an alternate form that is useful in certain circumstances: 
 List cats = sess.createCriteria(Cat.class)
§      .createAlias("kittens", "kt")
§      .createAlias("mate", "mt")
§      .add( Restrictions.eqProperty("", "") )
§      .list();

(createAlias() does not create a new instance of Criteria.)
The kittens collections held by the Cat instances returned by the previous two queries are not pre-filtered by the criteria. If you want to retrieve just the kittens that match the criteria, you must use aResultTransformer.
 List cats = sess.createCriteria(Cat.class)
§      .createCriteria("kittens", "kt")
§          .add( Restrictions.eq("name", "F%") )
§      .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
§      .list();
§  Iterator iter = cats.iterator();
§  while ( iter.hasNext() ) {
§      Map map = (Map);
§      Cat cat = (Cat) map.get(Criteria.ROOT_ALIAS);
§      Cat kitten = (Cat) map.get("kt");
§  }

 §  Dynamic association fetching
§  You can specify association fetching semantics at runtime using setFetchMode().
 List cats = sess.createCriteria(Cat.class)
§      .add("name", "Fritz%") )
§      .setFetchMode("mate", FetchMode.EAGER)
§      .setFetchMode("kittens", FetchMode.EAGER)
§      .list();

§  Example queries
§  The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance.
  Cat cat = new Cat();
§  cat.setSex('F');
§  cat.setColor(Color.BLACK);
§  List results = session.createCriteria(Cat.class)
§      .add( Example.create(cat) )
§      .list(); 

  Version properties, identifiers and associations are ignored. By default, null valued properties are excluded.  

    You can adjust how the Example is applied.
                Example example = Example.create(cat)
§      .excludeZeroes()           //exclude zero valued properties
§      .excludeProperty("color")  //exclude the property named "color"
§      .ignoreCase()              //perform case insensitive string comparisons
§      .enableLike();             //use like for string comparisons
§  List results = session.createCriteria(Cat.class)
§      .add(example)
§      .list();

    You can even use examples to place criteria upon associated objects.
            List results = session.createCriteria(Cat.class)
§      .add( Example.create(cat) )
§      .createCriteria("mate")
§          .add( Example.create( cat.getMate() ) )
§      .list(); 

§  Projections, aggregation and grouping
§  The class org.hibernate.criterion.Projections is a factory for Projection instances. You can apply a projection to a query by calling setProjection().
                List results = session.createCriteria(Cat.class)
§      .setProjection( Projections.rowCount() )
§      .add( Restrictions.eq("color", Color.BLACK) )
§      .list();
§  List results = session.createCriteria(Cat.class)
§      .setProjection( Projections.projectionList()
§          .add( Projections.rowCount() )
§          .add( Projections.avg("weight") )
§          .add( Projections.max("weight") )
§          .add( Projections.groupProperty("color") )
§      )
§      .list();

         There is no explicit "group by" necessary in a criteria query. Certain projection types are defined to begrouping projections, which also appear in the SQL group by clause.
An alias can be assigned to a projection so that the projected value can be referred to in restrictions or orderings. Here are two different ways to do this:
                 List results = session.createCriteria(Cat.class)
§      .setProjection( Projections.alias( Projections.groupProperty("color"), "colr" ) )
§      .addOrder( Order.asc("colr") )
§      .list();
§  List results = session.createCriteria(Cat.class)
§      .setProjection( Projections.groupProperty("color").as("colr") )
§      .addOrder( Order.asc("colr") )
§      .list();
     The alias() and as() methods simply wrap a projection instance in another, aliased, instance of Projection. As a shortcut, you can assign an alias when you add the projection to a projection list:
                  List results = session.createCriteria(Cat.class)
§      .setProjection( Projections.projectionList()
§          .add( Projections.rowCount(), "catCountByColor" )
§          .add( Projections.avg("weight"), "avgWeight" )
§          .add( Projections.max("weight"), "maxWeight" )
§          .add( Projections.groupProperty("color"), "color" )
§      )
§      .addOrder( Order.desc("catCountByColor") )
§      .addOrder( Order.desc("avgWeight") )
§      .list();
§  List results = session.createCriteria(Domestic.class, "cat")
§      .createAlias("kittens", "kit")
§      .setProjection( Projections.projectionList()
§          .add(""), "catName" )
§          .add(""), "kitName" )
§      )
§      .addOrder( Order.asc("catName") )
§      .addOrder( Order.asc("kitName") )
§      .list(); 
  You can also use Property.forName() to express projections:

            List results = session.createCriteria(Cat.class)
§      .setProjection( Property.forName("name") )
§      .add( Property.forName("color").eq(Color.BLACK) )
§      .list();
§  List results = session.createCriteria(Cat.class)
§      .setProjection( Projections.projectionList()
§          .add( Projections.rowCount().as("catCountByColor") )
§          .add( Property.forName("weight").avg().as("avgWeight") )
§          .add( Property.forName("weight").max().as("maxWeight") )
§          .add( Property.forName("color").group().as("color" )
§      )
§      .addOrder( Order.desc("catCountByColor") )
§      .addOrder( Order.desc("avgWeight") )
§      .list(); 
    Detached queries and subqueries
§  The DetachedCriteria class allows you to create a query outside the scope of a session and then execute it using an arbitrary Session.
                 DetachedCriteria query = DetachedCriteria.forClass(Cat.class)
§      .add( Property.forName("sex").eq('F') );
§  Session session = ....;
§  Transaction txn = session.beginTransaction();
§  List results = query.getExecutableCriteria(session).setMaxResults(100).list();
§  txn.commit();
§  session.close(); 

§  DetachedCriteria can also be used to express a subquery. Criterion instances involving subqueries can be obtained via Subqueries or Property.

                   DetachedCriteria avgWeight = DetachedCriteria.forClass(Cat.class)
§      .setProjection( Property.forName("weight").avg() );
§  session.createCriteria(Cat.class)
§      .add( Property.forName("weight").gt(avgWeight) )
§      .list();
§  DetachedCriteria weights = DetachedCriteria.forClass(Cat.class)
§      .setProjection( Property.forName("weight") );
§  session.createCriteria(Cat.class)
§      .add( Subqueries.geAll("weight", weights) )
§      .list();

  Correlated subqueries are also possible:
 DetachedCriteria avgWeightForSex = DetachedCriteria.forClass(Cat.class, "cat2")
§      .setProjection( Property.forName("weight").avg() )
§      .add( Property.forName("").eqProperty("") );
§  session.createCriteria(Cat.class, "cat")
§      .add( Property.forName("weight").gt(avgWeightForSex) )
§      .list();

  Queries by natural identifier
§  For most queries, including criteria queries, the query cache is not efficient because query cache invalidation occurs too frequently. However, there is a special kind of query where you can optimize the cache invalidation algorithm: lookups by a constant natural key. In some applications, this kind of query occurs frequently. The criteria API provides special provision for this use case.
First, map the natural key of your entity using <natural-id> and enable use of the second-level cache.

               <class name="User">
§      <cache usage="read-write"/>
§      <id name="id">
§          <generator class="increment"/>
§      </id>
§      <natural-id>
§          <property name="name"/>
§          <property name="org"/>
§      </natural-id>
§      <property name="password"/>
§  </class>

  This functionality is not intended for use with entities with mutable natural keys.
Once you have enabled the Hibernate query cache, the Restrictions.naturalId() allows you to make use of the more efficient cache algorithm.

§      .add( Restrictions.naturalId()
§          .set("name", "gavin")
§          .set("org", "hb")
§      ).setCacheable(true)

 . .uniqueResult();

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, high performance object/relational persistence and query service. It allows us to develop persistent classes following object-oriented idiom – including association, inheritance and polymorphism.

 Hibernate Architecture


1) itself opens connection to database,
2) converts HQL (Hibernate Query Language) statements to database specific statement,
3) receives result set,
4) then performs mapping of these database specific data to Java objects which are directly used by Java application.

Hibernate uses the database specification from Hibernate Properties file. Automatic mapping is performed on the basis of the properties defined in hbm XML file defined for particular Java object.

Hibernate communication with RDBMS

General steps:

1. Load the Hibernate configuration file and create configuration object. It will automatically load all hbm           mapping files.
2. Create session factory from configuration object
3. Get one session from this session factory.
4. Create HQL query.
5. Execute query to get list containing Java objects.

Example: Retrieve list of employees from Employee table using Hibernate. /* Load the hibernate configuration file */

Configuration cfg = new Configuration(); cfg.configure(CONFIG_FILE_LOCATION);

/* Create the session factory */

SessionFactory sessionFactory = cfg.buildSessionFactory();

/* Retrieve the session */

Session session = sessionFactory.openSession();

/* create query */

Query query = session.createQuery("from  EmployeeBean”);

/* execute query and get result in form of Java objects */ List finalList = query.list();

EmployeeBean.hbm.xml File

"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "">

Disadvantages of Hibernate:

1)     Steep learning curve.

Use of Hibernate is an overhead for the applications which are :

simple and use one database that never change
need to put data to database tables, no further SQL queries
there are no objects which are mapped to two different tables
Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.

Support for Hibernate on Internet is not sufficient.

Anybody wanting to maintain application using Hibernate will need to know Hibernate.

For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.

Hibernate does not allow some type of queries which are supported by JDBC. For example It does not allow to insert multiple objects (persistent data) to same table using single query. Developer has to write separate query to insert each object.

Hibernate load( ) vs get( )

The following Hibernate code snippet retrieves a User object from the database:

1). Only use the load() method if you are sure that the object exists.
2). load() method will throw an exception if the unique id is not found in the database.
3). load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.
    get( )
1). If you are not sure that the object exists, then use one of the get() methods.
2). get() method will return null if the unique id is not found in the database.
3). get() will hit the database immediately. 



What is lazy loading in Hibernate?

Lazy setting decides whether to load child objects while loading the Parent Object.You need to do this setting respective hibernate mapping file of the parent class.lazy = true (means not to load child)By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent.In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object.But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
                                Example: lazy=true (default)Address child of User class can be made lazy if it is not required frequently. lazy=false but you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.

Lazy fetching means for example in hibernate if we use load() method then load() is lazy fetching i.e it is not going to touch the database until we write empobject.getString( eno );So when we write above statement in that instance it touch the database and get all the data from database. It is called as lazy loading.If we see another example i.e session.get(...) method is used then at that instance it is going to touch the database and get the data and place the data in session object it is called as eager loading.

Hibernate Caching Techniques

Caching is a Temporary memory or buffer which resides at client side and stores the results sent by server. When client generates same request for multiple number of times, the first request generated results will be stored in cache and this result will be used across the multiple requests. This reduces the round trips between the client and server. Since the result will be collected from cache that is available at client side.
Hibernate supports for 2 levels of cache:
  1. Level one cache
  2. Level two cache.

Level One Cache:
Level 1 cache is inbuilt cache and it will be associated with hibernate session objects. Every session object of hibernate application contains one inbuilt level one cache.

Responsibilities of Level one cache:
a)      If select query executed for multiple no of times with in a session. Only one time query goes to database software gets the result, remaining all the times result will be gathered from cache.
b)      If one of pojo class object is modified for multiple no of times with in a transaction of session object, instead of sending update query for multiple number of times, all the changes done on the object wil be kept tracked and only one update query wil be generated reflecting all the changes at the end of the transaction.
The different ways to remove the level 1 cache from session

i)  Session.flush() –>  Flushes level one cache content to db software
ii)  Session.evict() –> Remove the content of level 1 cache
iii) Session.close() –> closes level 1 cache, before that it calls session.flush()

A hibernate client application can have multiple level1 caches because a hibernate application can have multiple hibernate session objects.
The data stored in level1 cache, level2 cache will be in full synchronization with table rows.
Level-2 Cache:

It is a configurable cache (Not a built in cache). Third party vendors are supplying supporting jar files for level 2 cache. Level2 cache is global cache and it is visible for all the session objects of the hibernate application.
When level-2 cache is enabled the results gathered for database software will be stored in both level 1 and level 2 caches.

sessionFactory.close() –> Destroys the session factory object and releases level 2 cache.
sessionFactory.evict(arga …) –> Removes pojo class object from session factory.
sessionFactory.evictQueries(args…) –> Cleans queries related data from cache.

If hibernate use same request as second request or different session objects then software tries to collects the results either from leve1/level2 caches.
There are different third party providers for level 2 cache:
  1. Swarm Cache
  2. OS Cache,
  3. EH Cache
  4. JBoss Tree Cache … etc.

Simple Hibernate Example on Inserting Employee details using MySql

Hibernate is a solution for object relational mapping and a persistence management solution or persistent layer. This is probably not understandable for anybody learning Hibernate.

What you can imagine is probably that you have your application with some functions (business logic) and you want to save data in a database. When you use Java all the business logic normally works with objects of different class types. Your database tables are not at all objects.

Hibernate provides a solution to map database tables to a class. It copies the database data to a class. In the other direction it supports to save objects to the database. In this process the object is transformed to one or more tables.

Saving data to a storage is called persistence. And the copying of tables to objects and vice versa is called object relational mapping.

Example program on Hibernate.

Required jars to run simple hibernate program.


download the jar files of Hibernate.
To run the Hibernate program we need four elements or files.
They are:
3.pojoclass.hbm.xml (with main method)

In our Example the files are:

In our example we are using MySql database.For that we need the driver_class,connection_url,username,password,MySqldialect.
These are configured in hibernate.cfg.xml file to configure the MySql database. 
?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://</property>
        <property name="connection.username">test</property>
        <property name="connection.password">test</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Mapping files -->
        <mapping resource="com/javabynataraj/empdet.hbm.xml"/>


Then by providing mapping to the java pojo class to database table we can do the operations whether inserting the data or updating or deleting using Session,SessionFactory,Transaction interfaces and Configuration class.

The pojo class Example: 
package com.javabynataraj;


public class Empdet implements Serializable{
 int eno;
 String ename;
 int esal;
 String eadd;
 public Empdet(){
 public int getEno() {
  return eno;
 public void setEno(int eno) {
  this.eno = eno;
 public String getEname() {
  return ename;
 public void setEname(String ename) {
  this.ename = ename;
 public int getEsal() {
  return esal;
 public void setEsal(int esal) {
  this.esal = esal;
 public String getEadd() {
  return eadd;
 public void setEadd(String eadd) {
  this.eadd = eadd;

Only the data is going to inserted or updated scenarios we use Transaction ,for select query we don't use Transaction.

Write  a pojo class to get and set the values from database and the user.And we can do serialize the pojo class object .And we have to write a constructor for this class additionally.

We have taken here four variables based on table in database.
    int eno;
    String ename;
    int esal;
    String eadd;

And Map the pojo calss names and database table columns in empdet.hbm.xml as below given:
Java Persistence with Hibernate

!DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"


<class name="com.javabynataraj.Empdet" table="empdet">
 <id name="eno" type="int" column="eno">
  <generator class="increment"/>
 <property name="ename" type="string" column="ename" />
 <property name="esal" type="int" column="esal" />
 <property name="eadd" type="string" column="eadd" />


      T he final step is writing Clientfile( insert employee details in the database table using pojo class. 
mport org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Empdetails {
 public static void main(String[] args) {
  Configuration conf = new Configuration().configure();
  SessionFactory factory = conf.buildSessionFactory();
  Session session = factory.openSession();
  Transaction tx = session.beginTransaction();
  Empdet edet = new Empdet();
  System.out.println("The data has been saved......");

    After running your Client file ( normal java program.then you will display with hibernate query and the last given print statement.
based on given primary key generation the eno will generate automatically by increment order.

Hibernate Configuration file (hibernate.cfg.xml) in Detail

Hibernate Configuration file for SQLyog.

Before configuring the properties of hibernate.cfg.xml we should mention the xml schema definitions of hibernate-configurations.The dtd defines the version and everything which is licensed.

To configure with database to our application we should give all the properties related to our database.The given properties of hibernate-configuration.


These are the minimum and compulsory properties to give in our cfg.xml file.

Every database having it's own driver class and url.Collect that depends on database and configure for it.

The username and password are of your current database you can use.

Connection pool size we should mention to increase the capacity of connections at runtime if more connectins required.

Dialect property tells which database we are using to interact with hibernate.The name of the Dialect .Hibernate community has given several dialect names based on different Databases.

They are:

    DB2 - org.hibernate.dialect.DB2Dialect
    HypersonicSQL - org.hibernate.dialect.HSQLDialect
    Informix - org.hibernate.dialect.InformixDialect
    Ingres - org.hibernate.dialect.IngresDialect
    Interbase - org.hibernate.dialect.InterbaseDialect
    Pointbase - org.hibernate.dialect.PointbaseDialect
    PostgreSQL - org.hibernate.dialect.PostgreSQLDialect
    Mckoi SQL - org.hibernate.dialect.MckoiDialect
    Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect
    MySQL - org.hibernate.dialect.MySQLDialect
    Oracle (any version) - org.hibernate.dialect.OracleDialect
    Oracle 9 - org.hibernate.dialect.Oracle9Dialect
    Progress - org.hibernate.dialect.ProgressDialect
    FrontBase - org.hibernate.dialect.FrontbaseDialect
    SAP DB - org.hibernate.dialect.SAPDBDialect
    Sybase - org.hibernate.dialect.SybaseDialect
    Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

The property is the mapping for our register table.

here i have configured the properties for SQLyog
<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"



  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://</property>
  <property name="hibernate.connection.username">test</property>
  <property name="connection.password">test</property>
  <property name="connection.pool_size">10</property>
  <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
  <property name="show_sql">true</property>
  <property name="">update</property>

  <mapping resource="com/javabynataraj/register/dao/pojos/RegisterUser.hbm.xml" />



1)      Explain about Hibernate?

Hibernate solves problems such as Object Relational impedance mismatch, etc. It is commonly used for object and query service. It helps data base developers develop classes which include inheritance, association, composition and polymorphism. A developer or user can express queries either in HQL or SQL.

2) Explain about the primary feature of Hibernate?

Primary feature of hibernate is to java classes to database tables. Data query and retrieval is also possible with
Hibernate. Application portability is a key feature in Hibernate it allows developers to port applications to almost all SQL databases.

3) Explain about transparent persistence of Hibernate?

Transparent persistence is provided for Plain old Java objects or POJOs. For proper functioning of the applications importance should be given to the methods equals () and hash Code methods (). It has a requirement which should be strictly followed in the applications which is a no-argument constructor.
4) Explain about the dirty checking feature of Hibernate?

Dirty checking feature of the Hibernate allows users or developers to avoid time consuming data base write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched.

5) Brief about the Session factory interface?

It creates new hibernate sessions by referencing immutable and thread safe objects. Application using hibernate are usually allowed and desgined to implement single instance of the class using this interface. Only single instance of a class can be used which is using this interface.

6) Explain about session interface?

This represents hibernate session which perform the manipulation on the database entities. Some of the activities performed by session interface are as follows they are managing the persistence state, fetching persisted ones and management of the transaction demarcation.

7) Explain the steps involved in creating database applications with Java using Hibernate?

Creating Database applications with Java is made simpler with Hibernate. First Plain old java object needs to be written, XML mapping file should be created which shows relationship between database and class attributes. Hibernate APIs can be used to store persistent objects.

8) Explain about hibernate.cfg.xml?

Hibernate can be configured with two types of files out of which hibernate.cfg.xml is widely used and popular feature. Hibernate consults hibernate.cfg.xml file for its operating properties such as database dialect, connection string and mapping files. These files are searched on class path.

9) Explain about mapping description file?

Mapping description file is the second file which Hibernate uses to configure its functions. This mapping file has an extension *.hbm which instructs mapping between Java class and database tables. The usage of mapping description file rests entirely upon the business entity.

10) Explain about transaction file?

Transactions denote a work file which can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA or JTA. When this session starts several transactions may occur.
11) Explain about mapping files in Hibernate?

Mapping files forms the core of any database mapping tools. These files contain field to field mapping, usually this mapping occurs between classes and attributes. After mapping files they can be persist to the database. Tags can be used to indicate the presence of a primary key.
12) What is the effect when a transient mapped object is passed onto a Sessions save?

When a ) is passed to a transient mapped object it makes the method to become more persistent. Garbage collection and termination of the Java virtual machine stays as long as it is deleted explicitly. It may head back to its transient state.

13) Explain about version field?

Application level data integrity constants are important if you are making changes to offline information which is again backed by database. Higher level locking or versioning protocol is required to support them. Version field usage comes at this stage but the design and implementation process is left to the developer.

14) State some advantages of hibernate?

Some of the advantages which a developer can get from Hibernate are as follows:
Mapping of one POJO table to one table is not required in hibernate.
It supports inheritance relationships and is generally a fast tool. Portability is necessary the greater benefit from hibernate. POJOs can be used in other applications where they are applicable.

15) Explain about addClass function?

This function translates a Java class name into file name. This translated file name is then loaded as an input stream from the Java class loader. This addclass function is important if you want efficient usage of classes in your code.

16) Explain about addjar() and addDirectory() methods?

These methods are the most convenient to use in hibernate. These methods allow you to load all your Hibernate documents at a time. These methods simplify code configuration, refactoring, layout, etc. These functions help you to add your hibernate mapping to Hibernate initialization files.

17) Explain about the id field?

This id field corresponds to the surrogate key which is generated by the database. These fields are handled by the id field. Name attribute is used to specify the names of the field and it should correspond to the method name of getid. This also should correspond to long type and the values should be stored I the database in the long column.

18) What are the most common methods of Hibernate configuration?

 The most common methods of Hibernate configuration are:
* Programmatic configuration
* XML configuration (hibernate.cfg.xml)

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

20) What are the Core interfaces are of Hibernate framework?

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
* Transaction interface
* Query and Criteria interfaces
21) 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 up objects by identifier

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

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

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

25) How do you map Java Objects with Database tables?

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

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

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

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.

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

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.

29) How do you define sequence generated primary key in hibernate?

A) Using tag.

30) Define cascade and inverse option in one-many mapping?

A) cascade – enable operations to cascade to child entities.
inverse – mark this collection as the “inverse” end of a bidirectional association.
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?
31) 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).

32) What do you mean by Named – SQL query?

A) Named SQL queries are defined in the mapping xml document and called wherever required.


SELECT emp.EMP_ID AS {emp.empid},
emp.EMP_ADDRESS AS {emp.address},
emp.EMP_NAME AS {}
FROM Employee EMP WHERE emp.NAME LIKE :name

Invoke Named Query :
List people = session.getNamedQuery(“empdetails”).setString(“TomBrady”, name).setMaxResults(50).list();

33) How do you invoke Stored Procedures?

A) { ? = call selectAllEmployees() }

34) Explain Criteria API?

A) 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(“name”, “a%”) )
.add(“address”, “Boston”))
.addOrder(Order.asc(“name”) )

35) Define HibernateTemplate?

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

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

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

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

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

40) 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
41) What is the difference between sorted and ordered collection in hibernate?

A) sorted collection vs. order collection
sorted 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 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 .

42) How will you configure Hibernate?


The configuration files hibernate.cfg.xml (or 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 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 settings found in the 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.

43) What is a SessionFactory? Is it a thread-safe object?


SessionFactory is Hibernate s 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 application code.

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

44) What is a Session? Can you share a session object between different theads? 

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 {
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();
return session;

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

45) What are the benefits of detached objects?


Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

46) What are the pros and cons of detached objects? 


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


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

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

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

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

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

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

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

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

51) What are Collection types in Hibernate?

? ArrayType,
Constructor: ArrayType(String role, String propertyRef, Class elementClass, boolean isEmbeddedInXML)
? BagType,
Constructor: BagType(String role, String propertyRef, boolean isEmbeddedInXML)
? CustomCollectionType, A custom type for mapping user-written classes that implement PersistentCollection
Constructor: CustomCollectionType(Class userTypeClass, String role, String foreignKeyPropertyName, boolean isEmbeddedInXML)
? IdentifierBagType,
Constructor: IdentifierBagType(String role, String propertyRef, boolean isEmbeddedInXML)
? ListType,
Constructor: ListType(String role, String propertyRef, boolean isEmbeddedInXML)
? MapType,
Constructor: MapType(String role, String propertyRef, boolean isEmbeddedInXML)
? SetType
Constructor: SetType(String role, String propertyRef, boolean isEmbeddedInXML)

No comments:

Post a Comment