Hibernate

Hibernate Subjective Questions And Answers
More interview questions and answers

What is Persistence?

Persistence is one of the fundamental concepts in application development. In an object-oriented application, persistence allows an object to outlive the process that created it. The state of the object may be stored to disk and an object with the same state re-created at some point in the future. 
Persistence is the ability of data to outlive an instance of a program, central to modern applications. Hibernate, the most popular Java persistence tool, provides automatic and transparent object/relational mapping so it\'s a snap to work with SQL databases in Java applications.

What is Hibernate?

Hibernate is popular open source object relational mapping tool for Java platform. It provides powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework.

What is ORM? What does ORM consists of?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.
An ORM solution consists of the followig four pieces:

    * API for performing basic CRUD operations
    * API to express ries refering to classes
    * Facilities to specify metadata
    * Optimization facilities : dirty cecking, lazy associations fetching.

What Does Hibernate Simplify?

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

What are the most common methods of Hibernate configuration?

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

What are the Core interfaces are of Hibernate framework?

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

How to call stored procedure in mysql through hibernate?

If your stored procedure is returning a value you can directly use <sql-query>, otherwise you need to use jdbc connection to call the native sql procedure.

Example:
Session session = getHibernateTemplate().getSessionFactory().openSession();
/*if you are not using session factory, you can use ur own method to get session.*/
Connection conn = session.connection();
String sqlQuery = \"call VersionUpdateProcedure()\";
CallableStatement cs = conn.prepareCall(sqlQuery);
cs.execute();
conn.close();
session.close();

what is lazy initialisation in hibernate?

Hibernate supports the feature of lazy initialization for both entities and collections. What this actually means is, the Hibernate engine loads only those objects that we are querying for and doesnt try to fetch other entities(that are associated with the entity we are querying) or collections.

Hibernate loads collection elements only when actually you ask for them by saying lazy=true or lazy=false.
Example:
<set name=\"Child\" lazy=\"false\" inverse=\"true\">
  <key column=\"COL\"/>
  <one-to-many class=\"Parent\"/>
</set>

What is Hibernate proxy?

Proxies are the mechanism that allows Hibernate to break up the interconnected cloud of objects in the database into smaller chunks, that can easily fit in memory. Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the method for you. A class can be mapped to a proxy instead to a table. When you actually call load on session it returns you proxy. This proxy may contain actual method to load the data.
Object proxies can be defined in one of two ways. First, you can add a proxy attribute to the class element. You can either specify a different class or use the persistent class as the proxy.
For example:
   <class name=\"Location\"
   proxy=\"com.ch01.Location\">
   </class>
The second method is to use the lazy attribute. Setting lazy=\"true\"is a shorthand way of defining the persistent class as the proxy. Let\'s assume the Location class is defined as lazy:

   <class name=\"Location\"lazy=\"true\"...>...</class>

What is the main difference between Entity Beans and Hibernate ?

In an Entity Bean, we can interact with only one Database at a time. Whereas in Hibernate, we can established the connections to more than one Database. Only thing we need to write one more configuration file.
Entity Beans does not support OOPS concepts where as Hibernate does. Hibernate supports multi level caching, where as Entity Beans doesn\'t.

What role does the Session interface play in Hibernate?

The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not threadsafe. 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 ry objects to retrieve persistent objects.

Session session = sessionFactory.openSession();


Session interface play roles in:
  * 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.

How will you configure Hibernate?

The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create the SessionFactory, which in turn creates the Session instances.
  hibernate.cfg.xml
  Mapping files
These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc).

Is SessionFactory a thread safe object ?

Yes! SessionFactory object is threadsafe. Many threads can request for session and immutable cache of compiled mappings for a single database. 

What are different levels of ORM quality?

There are four levels defined for ORM quality:
  * Pure relational: The entire application, including the UI is designed around the relational model and SQL based relational operation.
  * 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.
  * Medium Object Mapping: The application is designed around an object model. The SQL code is generated at build time, and the association between objects is 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.
  * Full Object Mapping: Full Object Mapping supports sophisticated object modeling, composition, inheritance, polymorphism and persistence.

What is Hibernate Query Language (HQL)?

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

What are derived properties?

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 formula attribute of the element. 

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. 
Example :
<hibernate-mapping>
  <class name=\"com.User\"  table=\"user\">
   <property  column=\"username\" length=\"255\"
      name=\"userName\" not-null=\"true\"  type=\"java.lang.String\"/>
   <property  column=\"userpassword\" length=\"255\"
     name=\"userPassword\" not-null=\"true\"  type=\"java.lang.String\"/>
 </class>
</hibernate-mapping>

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.
    * Create session factory from configuration object.
    * Get one session from this session factory
    * Create HQL Query.
    * Execute query to get list containing Java objects.

Define HibernateTemplate?

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

How will you obtain a session factory?

After all mappings have been parsed by the org.hibernate.cfg.Configuration, the application must obtain a factory for org.hibernate.Session instances. This factory is intended to be shared by all application threads:

SessionFactory sessions = cfg.buildSessionFactory();

Hibernate does allow your application to instantiate more than one org.hibernate.SessionFactory. This is useful if you are using more than one database.

What are the types of inheritence models in Hibernate?

There are three types of inheritance mapping in hibernate:
  1. Table per concrete class with unions.
  2. Table per class hierarchy.
  3. Table per subclass.

Explain the various object states in Hibernate?

Hibernate defines and supports the following object states: 
  * Transient :- an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned.
  * Persistent :- a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.
  * Detached :- a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it persistent again.

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. 

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

The EmptyInterceptor class provides the isTransient() method to check whether the object is transient or deteched. Method signature:
  java.lang.Boolean isTransient(java.lang.Object obj)

Does Hibernate implement its functionality using a minimal number of database queries?

Hibernate can make certain optimizations implement its functionality using a minimal number of database queries:
  * Caching objects
  * Executing SQL statement when needed.
  * Never updating unmodified objects.
  * Efficient Collection Handling.
  * Updating only the modified columns.
  * Outer join fetching.
  * Lazy collection initialization.
  * Lazy object initialization.

How can we get access to O/R mapping information such as table and column names at runtime?

This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.

Aren\'t stored procedures always faster than dynamic SQL?

No! Hibernate always executes SQL statements using a JDBC PreparedStatement, which allows the database to cache the query plan. There is no reason to avoid the use of generated SQL in modern applications.

Does Hibernate fully support polymorphism?

Hibernate supports polymorphic queries and associations in all three inheritance mapping strategies (and even allows mixing of the two most important strategies).

What are the different Transaction Factories available with Hibernate?

There are three different types of Transaction Factoryavailable with Hibenate 3.2 are :
  * JDBCTransactionFactory,
  * JTATransactionFactory, and
  * CMTTransactionFactory.

What are the different Fetching Strategies available with Hibernate?

There are four different Fetching standards available in Hibernate3.2:
  * join fetching,
  * select fetching,
  * batch fetching,
  * sub-select fetching.

What are the different types of statistics available in Hibernate 3.2?

Different types of statistics available in Hibernate:
  * QueryStatistics,
  * CategorizedStatistics,
  * CollectionStatistics,
  * EntityStatistics, etc.

How can multiple threads access session factory simulteneously to create session instance?

We know that the session factory is thread-safe, so it is okay to use SessionFactory object by many threads to have session from session factory, but I think session is not thread safe and it should be used by one thread at a time, and after use, session has to be flushed and closed.

Can you tell us difference between Hibernate HQL over SQL?

HQL (Hibernate Query Language) is fully object oriented, with support for object inheritence, polymorphism and association, but SQL (Structure Query Language) is more of Relational with structured form of queries.

Difference between session.update() and session.lock() in Hibernate ?

Both the session.update() and session.lock() are intended for re-attaching 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.

What is the best application framework for use with Hibernate?

Both the session.update() and session.lock() are intended for re-attaching 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. 

Explain about the dirty checking feature of Hibernate?

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

Explain about mapping description file?

Hibernate can be configured with two types of files out of which hibernate.cfg.xml is the mapping description file in 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.

What�s the difference between load() and get()?

Both load() and get() methods used to find out the object in cache or database. Use get() method if you are not sure that the object exists. The get() method will return null if the unique id is not found in the database. The get() will hit the database immediately.

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

Explain Hibernate Transaction API?

The Transaction interface provides methods for declaring the boundaries of a database transaction.
Example:
Session s = sessions.openSession();
Transaction t = null;
try{
   t = s.beginTransaction();
   concludeAuction();
    t.commit();
   } catch(Exception e) {
      if(t!=null) {
         try{
            t.rollback();
            } catch (HibernateException h) {
               // log h and rethrow e
            }
       }
       throw e;
}finally {
   try{
      s.close();
      } catch (HibernateException h) {
         throw h;
      }
}

What auto commint mode should you use in JDBC connection in Hibernate?

A magical setting that is often a source of confusion is the JDBC connection\'s auto commit mode. If a database connection is in auto commit mode, the database transaction will be committed immediately after each SQL statement, and a new transaction will be started. This can be useful for ad hoc database queries and ad hoc data updates.

What are the various advanced configuration techniques in Hibernate?

Advanced configuration techniques in Hibernate:
  * Using XML-based configuration :
  <hibernate-configuration>
    <session-factory>
        <!-- properties -->
        <property name= \"dialect\">org.hibernate.dialect.MySQL5Dialect</property>
        <property name=\"connection.datasource\">java:comp/env/jdbc/yourDatabase</property>
        <property name=\"show_sql\">true</property>
        <property name=\"use_outer_join\">true</property>
        <property name=\"transaction.factory_class\">org.hibernate.transaction.JDBCTransactionFactory</property>
        <property name=\"current_session_context_class\">thread</property>


<!-- mappings -->
     <mapping class=\"com.MyProject.model.User\" />
</session-factory>
</hibernate-configuration>
 
  * JNDI-bound SessionFactory
  * Logging
  * Java Management Extensions (JMX)

What is JNDI-bound SessionFactory in Hibernate?

A JNDI bound Hibernate SessionFactory can simplify the lookup of the factory and the creation of new Sessions. If you wish to have the SessionFactory bound to a JNDI namespace, specify a name (eg. java:comp/env/hibernate/SessionFactory) using the property hibernate.session_factory_name. If this property is omitted, the SessionFactory will not be bound to JNDI. When binding the SessionFactory to JNDI, Hibernate will use the values of hibernate.jndi.url, hibernate.jndi.class to instantiate an initial context. If they are not specified, the default InitialContext  will be used. 

What is Java Management Extension (JMX) in Hibernate?

JMX is standard API for managing the Java application and components. JMX is a management technology that can be used to manage any kind of resource. The JMX technology provides the tools for building distributed, Web-based, modular and dynamic solutions for managing and monitoring devices, applications, and service-driven networks. 
There have been various management technologies in the market for Network and Telephonic Domains. Though JMX is not specifically oriented towards any domain, it can be used to manage and monitor resources in any domain. The major levels defined in JMX are:  
  * Instrumental Level  
  * Agent Level  
  * Remote Management Level

what is CaveatEmptor application in Hibernate?

CaveatEmptor\'s primary purpose is to educate on how to build a persistence service/layer with Hibernate. CaveatEmptor is an online auction application with business objects such as Item, User, and Bid. The domain model covers various kinds of entities, entity associations and collections. The Caveat Emptor is a simple book auction application built with XUI 3.1. It shows how to use the Hibernate POJO support in a two tiered scenario, where the Hibernate serves as a persistence layer (it is being used to directly connect to the database).

How will you map the metadata in configuration file in Hibernate?

In Hibernate 2.x, mapping metadata is most of the time declared in XML text files. Another option is XDoclet, utilizing Javadoc source code annotations and a preprocessor at compile time. The same kind of annotation support is now available in the standard JDK.
Hibernate mapping elements accept the node attribute. This let\'s you specify the name of an XML attribute or element that holds the property or entity data. The format of the node attribute must be one of the following:
    * element-name - map to the named XML element
    * attribute-name - map to the named XML attribute
    * .(dot) - map to the parent element
    * element-name/attribute-name - map to the named attribute of the named element.

What are the Transparent and Automated persistence in Hibernate?

Hibernate provides automatic and transparent object/relational mapping making it a snap to work with SQL databases in Java applications. 
Application server\'s CMP engine implements automated pesistence. It takes care of the tedious details of JDBC ResultSet and PreparedStatement handling.
The ability to directly manipulate data stored in a relational database using an object programming language is called transparent persistence. With transparent persistence, the manipulation and traversal of persistent objects is performed directly by the object programming language in the same manner as in-memory, non-persistent objects.

What is attribute oriented programming?

XDoclet is an open source code generation engine. It enables Attribute-Oriented Programming for java. In short, this means that you can add more significance to your code by adding meta data (attributes) to your java sources. This is done in special JavaDoc tags. 
XDoclet lets you apply Continuous Integration in component-oriented development. Developers should concentrate their editing work on only one Java source file per component.

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 that property. Hibernate applications works efficiently with POJOs rather then simple java classes. 

Where should SessionFactory be placed so that it can be easily accessed?

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. 

What are the different types of property and class mappings?

The different types of property and class mappings:
   * Typical and most common property mapping:
    <property name=\"Name\" column=\"firstName\" type=\"string\"/>
   Or
    <property name=\"Name\" type=\"string\">
        <column name=\"firstName\"/>
    </property>
    * Derived properties:
    <property name=\"averageAmount\" formula=\"( select AVG(b.AMOUNT) from TableName a where a.ITEM_ID = ITEM_ID )\" type=\"big_decimal\"/>
    * controlling inserts and updates:
    <property name=\"name\" column=\"NAME\" type=\"string\" insert=\"false\" update=\"false\"/>

What are the different methods of identifying an object?

There are three methods by which an object can be identified:
  * Object identity : Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator.
  * Object equality :Objects are equal if they have the same value, as defined by the equals( ) method. Classes that dont explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity.
  * 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.

What are managed associations and hibernate associations?

Associations are used to represent relationships between classes.  Managed association means that, if a change is made to one end of the association, it will be reflected at the other end. So when changes are made to the attributes participating in this association, they will be reflected at the other end automatically. The developer doesn\'t have to mange the associations manually. Hibernate mainly supports two types of associations:
  1. One-to-Many
  2. Many-to-One

What are the Extension interfaces that are there in hibernate?

There are many extension interfaces provided by hibernate:
  * ProxyFactory interface
  * ConnectionProvider interface
  * TransactionFactory interface
  * Transaction interface
  * TransactionManagementLookup interface
  * Cahce interface
  * CacheProvider interface
  * ClassPersister interface
  * IdentifierGenerator interface
  * Dialect abstract class.

What are different environments to configure hibernate?

There are mainly two types of environments in which the configuration of hibernate application differs:
  * 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.
  * 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.

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

The file extension you use for hibernate mapping file is \"filename.hbm.xml\".

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. Look how a SessionFactory is created when we use method chaining.
For Example:
   SessionFactory sessions = new Configuration().addResource(\"myinstance/MyConfig.hbm.xml\").setProperties
(System.getProperties()).buildSessionFactory();

How will you identify the database with Hibernate?

Hibernate exposes database identity to the application in two ways:
  * The value of the identifier property of a persistent instance.
  * The returned by Session.getIdentifier(Object o)
The Identifier property is special. Its value is the primary key value of the database row represented by the persistent instance.

Explain Fine-grained object model used in Hibernate?

A major objective of the Hibernate project is support for fine-grained object model. Fine-grained means \"more classes than tables\".
Hibernate emphasizes the usefulness of fine grained classes for implementing type safty and behaviour. 

What are the types of mapping class inheritance in Hibernate?

There are three different approaches to representing an inheritance hierarchy:
  * Table per concrete class: Discard polymorphism and Inheritance relationships completely from the relational model.
  * Table per class hierarchy: Enable polymorphism by denormalizing the relational model and using a type discriminator column to hold type information.
  * Table per sublcass: Represent \"is a\" (Inheritance) relationships as \"has a\" (foreign key) relationships.

What are the various services provided by the Persistence manager?

Any transparent persistent tool includes a persistence manager API, which usually provides services for:
  * Baxic CRUD operation
  * Query execution
  * Control of transaction
  * Management of the transaction-level cache.
The Persistence manager can be exposed by several different interfaces like Session, Query, Criteria, and Transaction. It provides the following services:
  * Making an object persistent
  * Updating the persistent state of a detached instance.
  * Retrieving a persistent object.
  * Updating a persistent object.
  * Making a persistent object transient.
  * Making a deteched object transient.

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

By using the session.merge() method call, you can reatach detached objects to a session when the same object has already been loaded into the session. 

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

The general considerations or best practices for defining your Hibernate persistent classes are:
  * You must have defined no-argument constructor, getters and setters method.
  * 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.
  * Implement the Serializable interface.
  * The persistent class should not be final.
  * Use XDoclet tags for generating your *.hbm.xml files or Annotations.

What is the difference between sorted and order collection in Hibernate?

A sorted ordered collection is stored in memory using Java Comparetor, whereas ordered collection is stored at the database level using orderby clause.

What is the main advantage of using Hibernate than sql?

The main advantage of using Hibernate over sql is that Hibernate avoids writing huge queries. Because most of the work is taken care by mapping and also criteria class is very useful for complex joins. We can also avoid JDBC API by using Hibernate.

How will you create a primary key using Hibernate?

The id field in hbm.xml file is used to specify the primary key in database. We can also use generator to specify the way primary key is generated to the database. 
For example
 <id name=\"StudentId\" type=\"string\" >
  <column name=\"columnId\" length=\"30\"/>
  <generator class=\"IdGenerator\"/>
 </id>
Here Id =\"StudentId\" act as primary key.

What is the difference between beans and Hibernate?

Hibernate uses POJO classes for handling persistence, these classes need to adhere normal bean writing. Beans are at form (view) level and Hibernate are at database level. 
JavaBeans are simple reusable component whereas hibernate are supports for the JavaBean object persistency.

What are the various ways to fetch objects from database in Hibernate?

Hibernate provides the following ways to get objects out of the database:
  * Navigating the object graph, starting from an already loaded object, by accessing the associated objects through property accessor methods.
  * Retrieving by Identifier.
  * Using the Hibernate Query Language (HQL).
  * Using the Hibernate Criteria API.
  * Using native SQL Queries.

How will you retrieve an object by Identifier from the database in Hibernate?

The following Hibernate code snippet retrieves a User defined Object form the database:
  User u = (User) session.get(User.class, userID);
The get() method is special because the identifier uniquely identifies a single instance of a class.

Hibernate also provides a load() method:
  User u = (User) session.load(User.class, userID);
If laod() method can\'t find the object in the cache or database, an exception is thrown. The get() method returns null if the object can\'t be found. The load() method may return a proxy instead of a real persistent instance.

Explain HQL (Hibernate Query Language)?

The HQL is an object oriented dialect of the familiar relational query language SQL. HQL is not a data manipulation language like SQL. It\'s used only for object retrieval, not for updating, inserting, or deleting data. HQL supports:
  * The ability to apply restrictions to properties of associated objects related by reference or held in collections.
  * The ability to retrieve only properties of an entity or entities.
  * The ability to order the results of the query.
  * The ability to paginate the results.
  * Aggregation with group by, having, and aggregate functions like sum, min, max.
  * Outer joins when retrieving multiple objects per row.
  * The ability to cal user-defined SQL functions.
  * Subqueries.

What is Hibernate QBC (Query By Criteria)?

The Hibernate Query By Criteria API lets you build a query by manipulating criteria objects at runtime. This approach lets you specify constraints dynamically without direct using mainpulations, but it doesn\'t lose much of the flexibility or power of HQL. 
Retrieving a user by first name is easy using a Criteria object:

Criteria c = session.createCriteria(User.class);
c.add(Expression.like(\"firstname\",\"Max\"));
List result = c.list();

What is Hibernate Query By Example?

The idea behind Query By Example is that the application supplies an instance of the queried class with certain property values set. The query returns all persistent instances with matching property values. QBE isn\'t a particularly powerful approach, but it can be convenient for some applications. The following code snippet demonstrates a Hibernate QBE:

User exampleUser = new User();
exampleUser.setFirstName(\"Max\");
Criteria c = session.createCriteria(User.class);
c.add(Example.create(exampleUser));
List r=criteria.list();

What are the various fetching strategies from the database in Hibernate?

Hibernate allows you to choose among four fetching strategies for any association, in association and at runtime:
  * Immediate fetching.
  * Lazy fetching.
  * Eager fatching.
  * Batch fetching.

What is outer join fetching in Hibernate?

Eager or outer join fetching lets you explicitly specify which associated objects should be loaded together with the referencing object. Hibernate can then return the associated objects in a single database request, utilizing an SQL OUTER JOIN.
Even though default eager fetching may be declared in the mapping file, it\'s more common to specify the use of this strategy at runtime for a particular HQL or criteria query.

What is Lazy fetching in Hibernate?

When a client request an entity and its association graph of object from the datebase. It isn\'t usually necessary to retrieve the dwhole graph. 
Lazy fetching lets you decide how much of the object graph is loaded in the first database hit and which associations should be loaded only when they\'re first accessed. Lazy fetching is a foundational concept in object persistence and the first step to attaining accetable performance.

How will you initialize lazy associations in Hibernate?

A proxy or collection wrapper is automatically initialized when any of its methods are invoked. However it is only possible to initialize a proxy or collection wrapper if it\'s currently associated with an open session. If you close the session and try to access an uninitialized proxy or collection, Hibernate throws a runtime exception.
Beacuase of this behaviour, it\'s sometimes useful to explicitly initialize an object before closing the session.
We use the static method Hibernate.initialize() for manual initialization:

 Session session = session.openSession();
 Transaction t = session.beginTransaction();
 Category cat = (Category)   
 session.get(Category.class, id);
 Hibernate.initialize(cat.getItems());
 t.commit();
 session.close();

Difference between getCurrentSession() and openSession() in Hibernate ?

A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs. The getCurrentSession() method looks at the current context to see if a session is stored in there. If there is one, it uses it, and if there isn\'t a session in the current context, it creates a new one and saves it in there.
On the other hand, openSession does not try to store the session, or pull the session from the current context.

What are the Collection types in Hibernate ?

The types of Collection  in Hibernate:
  *  Bag
  *  Set
  *  List
  *  Array
  *  Map

What is the difference between JDBC and JTA transactions in Hibernate?

In a non-managed environment, the JDBC API is used to mark transaction boundaries. You begin a transaction by calling setAutoCommit(false) on a JDBC connection and end it by calling commit(). You may, at any time, force an intermediate rollback by calling rollback().
In a system that stores data in multiple databases, you can\'t achieve atomaticity using JDBC alone. You require a transaction manager with support for distributed transactions (two-phase commit). You communicate with the transaction manager using the JTA (Java Transaction API).
In a managed environment, JTA is used only for distributed transaction, but also for declarative container managed transaction (CMT).

What are the various transaction isolation isssues in Hibernate?

The ANSI SQL standard defines the standart transaction isolation levels in terms of which of these phenomenon are permissible:
  * Last update
  * Dirty read
  * Unrepeatable read
  * Second lost updates problem
  * Phantom read

What is dirty read in transaction isolation issues?

When one transaction reads changes made by another transaction that hasn\'t yet been committed is called dirty read. This is very dangerous, because those changes might later be rolled back. 

Describe the various isolation levels defined by ANSI SQL standart?

The standart isolation levels are defined by the ANSI SQL standard but aren\'t particular to SQL databases:
  * Read uncommitted :- Permits dirty read but not lost updates. One transaction may not write to a row if another committed transaction has already written to it.
  * Read committed :- Permits unrepeatable reads but not dirty reads.
  * Repeatable reads :- Permits neither unrepeatable reads nor dirty reads. Phantom reads may occur.
  * Serializable :- Provides the strictest transaction isolation. It emulates serial transaction execution, as if transaction has been executed one after another, serially, rather than concurrently.

Explain the Phantom read?

A transaction executes a query twice, and the second result set includes rows that weren\'t visible in the first result set. This situation is caused by another transaction inserting new rows between the execution of the two queries.

How will you set the isolation level for database in JDBC connection?

Every JDBC connection to a database uses the database\'s default isolation level, usually read committed or repeatable read. This default can be changed in the database configuration. You may also set the transaction isolation for JDBC connection using a Hibernate configuration option:
  hibernate.connection.isolation = 4
Hibernate will then set this isolation level on every JDBC connection obtained from a connection pool before starting a transaction. The sensible values for this option are as follows:
  * 1-Read uncommitted isolation
  * 2-Read committed isolation
  * 4-Repeatable read isolation
  * 8-Serializable isolation

What are the various Catching strategies in Hibernate?

Catching is such a fundamental concept in object/ralational persistence that you can\'t understand the performance, scalability, or transactional semantics of an ORM implementation without first knowing what kind of catching strategy it uses. There are three types of cache:
  * Transaction scope :- Attached to the current unit of work, which may be an actual database transaction or an application transaction. Every unit of work has its own cache.
  * Process scope :- Shared among many unit of work or transaction.
  * Cluster scope :- Shared among multiple processes on the same machine or among the multiple machines in a cluster. It requires some kind of remote process communication to maintain consistency.

What are the various built-in concurrency strategies for transaction used in Hibernate?

A concurrency strategy is a mediator, it\'s responsible for storing items of data in the cache and retrieving them from the cache. There are four built in concurrency strategies, representing decreasing levels of strictness in terms of transaction isolation:
  * transactional :- Available in a managed environment only. It guarantees full transactional isolation upto repeatable read, if required.
  * read-write :- Maintains read committed isolation, using a timestamping mechanism. It\'s available only in non-clustered environments.
  * nonstrict-read-write :- Makes no guarantee of consistency between the cache and the database. If there is a possibility of concurrent access to the same entity , you should configure a sufficiently short expiry timeout. Otherwise you may read stale data in the catch.
  * read-only :- A concurrency strategy suitable for data which never changes. Use it for reference data only.

What are the various built-in-mapping types available in Hibernate?

Hibernate built-in mapping types usually share the name of the Java type they map; however, there may be more than one Hibernate mapping type for a partucular Java type. The various built-in-mapping types available in Hibernate are:
  * Java primitive mapping types
  * Date and time mapping types
  * Large object mapping types
  * Various JDK mapping types

What are the various mapping association in Hibernate?

When we use word associations, we are always referring to relationships between entities. The various mapping association in Hibernate:
  * One-to-one associations
  * Many-to-many association

Which interfaces are defined to execute the query in the Hibernate?

The following interfaces are defined to execute the query:
  * Query interface
  * Criteria interface
Both interfaces define several methods for controlling execution of a query.
To create a new Query instance, call either createQuery() or createSQLQuery(). The createQuery() method prepares an HQL query:
  Query q = session.createSQLQuery(
            \"select {u.*} from USERS {u}\", \"u\",
            User.class);

To obtain a Criteria instance, call createCriteria(), passing the class of the objects you want the quety to return. This is also called the root entity of the criteria query, the User in this example:
  Criteria c = session.createCriteria(User.class);

What are the Hibernate join options?

In Hibernate queries, you don\'t usually specify a join condition explicitly. Rather you specify the name of a mapped Java class association.
HQL provides four ways of expressing (inner and outer) joins:
  * An \'ordinary\' join in the \'from\' clause.
  * A \'fetch\' join in the \'from\' clause.
  * A \'theta-style\' join in the \'where\' clause.
  * An \'implicit\' association join.

Explain the Fetching association in HQL?

In HQL, you can specify that an association should be eagerly fetched by an outer join using the fetch keyword in the \'from\' clause:

  from Item item
  left join fetch item.bids
       where item.description like \'%gc\'

This query returns all items with a description that contains the string gc, and all their bids, in a single select. When executed, it returns a list of Item instances with there \'bids\' collection fully initialized. We call this a \'from\' clause.

What are the different caching services provided by the Hibernate?

Hibernate supports four different caching services.  EHCache (Easy Hibernate Cache) is the default service. If you prefer to use an alternative cache, you need to set the cache.provider_class property in the hibernate.cfg.xml file:

    <property name=\"cache.provider_class\">
      org.hibernate.cache.OSCacheProvider
    </property>
This snippet sets the cache provider to the OSCache caching service.

Caching Services Supported by Hibernate:
  * EHCache
  * OSCache
  * SwarmCache
  * TreeCache

What are the various advantages of Hibernate?

Advantages of Hibernate:
    * Retains natural object model (transparent)
    * Minimizes Code
    * Does not require a container
    * Model is not tied to persistence implementation.
    * Metadata controlled persistence
    * Transparent - working with the model, not the data access technology
    * Pooling, Caching, Transactions can all be handled outside of our code

What are the Joined Subclasses in Hibernate?

Joined subclasses are those that are mapped to a table-per-subclass design rather than a table-per-hierarchy. 
In Hibernate, this could be mapped as follows:

<class name=\"Foo\" table=\"foo\">
    ...
    <property name=\"name\" column=\"name\" type=\"string\"
    <joined-subclass name=\"subclass.Bar\" table=\"bar\">
         <key column=\"foo_id\"/>
         <property name=\"age\" column=\"age\" type=\"string\"/>
    </joined-subclass>
</class>

How will you configure the SessionFactory?

The Configuration class kicks off the runtime portion of Hibernate. It\'s used to load the mapping files and create a SessionFactory for those mapping files. There are three ways to create and initialize a Configuration object.
This first snippet loads the properties and mapping files defined in the hibernate.cfg.xml file and creates the SessionFactory:

    Configuration cfg =new Configuration();
    SessionFactory factory =cfg.configure().buildSessionFactory();
 
The configure()method tells Hibernate to load the hibernate.cfg.xml file.
The Configuration class can also load mapping documents programmatically:

    Configuration cfg =new Configuration();
    cfg.addFile(\"com/manning/hq/ch03/Event.hbm.xml\");
Another alternative is to have Hibernate load the mapping document based on the persistent class.

What is Connection pools used for in Hibernate?

Connection pools are a common way to improve application performance. Rather than opening a separate connection to the database for each request, the connection pool maintains a collection of open database connections that are reused. Application servers often provide their own connection pools using a JNDI DataSource, which Hibernate can take advantage of when configured to use a DataSource.
When you choose a connection pooling service, you must configure it for your environment. Hibernate supports configuring connection pools from the hibernate.cfg.xml file. The connection.provider_class property sets the pooling implementation:

    <property name=\"connection.provider_class\">
      org.hibernate.connection.C3P0ConnectionProvider
    </property>

How can you map a whole class as immutable?

You can mark the class as mutable=\"false\", Default value is true. This specifies that instances of the class are mutable. You can not update or delete immutable classes by the application.

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

You may declare a persistent class using the class element. The dynamic-insert and dynamic-update attributes are optional attributes. The  dynamic-update (defaults value is false), specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed.
The dynamic-insert (defaults value is false), specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

What are the types of Hibernate instance states ?

There are three types of instance states in Hibernate:
    * 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.

What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?

The settings of the XML configuration file will override the settings used in the properties.

Explain about HibernateTemplate?

The org.springframework.orm.hibernate.HibernateTemplate class simplifies Hibernate data access code, and converts checked HibernateExceptions into unchecked DataAccessExceptions, following the org.springframework.dao exception hierarchy. Uses the same SQLExceptionTranslator mechanism as JdbcTemplate. 
The central method is execute(), supporting Hibernate access code implementing the HibernateCallback interface. It provides Hibernate Session handling such that neither the HibernateCallback implementation nor the calling code needs to explicitly care about retrieving/closing Hibernate Sessions, or handling Session lifecycle exceptions.

Explained @Entity ,@Table,@Id and @Column annotations .

@Entity :-This annotation is used to make a entity (model) class. The annotation in javax.persistence.Entity class. 
@Table:-Used to map table name with POJO
@Id :-Is used to make  primary key column.Table must have a primary key without primary key we cant map . 
@Column :-map column name with java POJO  property 

e.g. 

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;



@Entity
@Table(name="BORROWER_PERSON_DETAILS")
public class BorrowerPersonDetail  {
	
	

	@Id
	@Column(name="BORROWER_PERSON_REF_ID")
	private String borrowerPersonRefId;
	
	@Column(name="BORROWER_REF_ID")
	private String borrowerRefId;


public String getBorrowerPersonRefId() {
		return this.borrowerPersonRefId;
	}

	public void setBorrowerPersonRefId(String borrowerPersonRefId) {
		if(borrowerPersonRefId!=null)
			this.borrowerPersonRefId = borrowerPersonRefId;
	}
public String getBorrowerRefId() {
		return this.borrowerRefId;
	}

	public void setBorrowerRefId(String borrowerRefId) {
		if(borrowerRefId!=null)
			this.borrowerRefId = borrowerRefId;
	}
}

Here we had created a POJO class named BorrowerPersonDetail to map is with table named BORROWER_PERSON_DETAILS .
This having two columns 1.BORROWER_PERSON_REF_ID is primary key 
 And 2. BORROWER_REF_ID .
We are making there two columns with borrowerPersonRefId and borrowerRefId 

Why Should one can use Hibernate?

Hibernate provide key features of it thats why it is good to use hibernate.

Performance: Hibernate can save your time and efforts, and it can let you achieve some performance gains that you could hardly ever achieve by hand-coding.

Portable: Application portability is a key feature in Hibernate it allows developers to port applications to almost all SQL databases. data query and retrieval is possible with hibernate.

Set of objects: Hibernate is set of objects we dont need to learn SQL ,here we can treat table as object. In case of JDBC we need to learn SQL.

Fast development: Development fast in case of Hibernate because you dont need to write queries. 
Get benefit of Cache: Hibernate support 2  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.

Open source code :- As open source so no need to pay.