Vous êtes sur la page 1sur 161

1) Introduction

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

Conclusion.

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

1.1) First-level cache


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

1.2) Second-level cache


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

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

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


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

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


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

2.3)SwarmCache (org.hibernate.cache.SwarmCacheProvider)
is a cluster-based caching. supports read-only or nonstrict read/write caching . appropriate for applications those have more read operations than write operations.

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


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

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

3.1) Read-only
Useful for data that is read frequently but never updated. It is Simple . Best performer among the all.

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

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

3.2) Read-Write
Used when our data needs to be updated. Its having more overhead than read-only caches. When Session.close() or Session.disconnect() is called the transaction should be completed in an environment where JTA is no used. It is never used if serializable transaction isolation level is required. In a JTA environment, for obtaining the JTA TransactionManager we must specify the property hibernate.transaction.manager_lookup_class. To use it in a cluster the cache implementation must support locking.

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

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

<cache usage="read-write"/> . </set> </class>

3.3) Nonstrict read-write


Needed if the application needs to update data rarely. we must specify hibernate.transaction.manager_lookup_class to use this in a JTA environment . The transaction is completed when Session.close() or Session.disconnect() is called In other environments (except JTA) .

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

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

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

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

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

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

<cache usage=" caching stringategy" region="RegionName" include="all | non-lazy"/> usage (mandatory) specifies the caching stringategy: transactional, read-write, nonstringict-read-write or read-only. region (optional) specifies the name of the second level cache region . include (optional) non-lazy specifies that properties of the entity mapped with lazy="true" may not be cached when attribute-level lazy fetching is enabled.

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

6) Caching the queries


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

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

List xyz = abc.createQuery("Query") .setEntity("",.) .setMaxResults(some integer) .setCacheable(true) .setCacheRegion("region name") .list(); We can cache the exact results of a query by setting the hibernate.cache.use_query_cache property in the hibernate.cfg.xml file to true as follows:

<property name="hibernate.cache.use_query_cache">true</property> Then, we can use the setCacheable() method on any query we wish to cache.

7) Custom Cache
To understand the relation between cache and the application the cache implementation

must generate statistics of cache usage.

7.1) Custom Cache Configuration


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

7.2) Implementation :: ExampleCustomCache


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

package examples.ExampleCustomCache; import net.sf.hibernate.cache; import java.util; import org.apache.commons.logging; public class ExampleCustomCache implements Cache { public Log log = LogFactory.getLog(ExapleCustomCache.class); public Map table = new Hashtable(100); int hits, misses, newhits, newmisses, locks, unlocks, remhits, remmisses, clears, destroys; public void statCount(StringBuffer input, String string1, int value) { input.append(string1 + " " + value); } public String lStats() { StringBuffer res = new StringBuffer(); statCount(res, statCount(res, statCount(res, statCount(res, statCount(res, statCount(res, statCount(res, statCount(res, statCount(res, statCount(res, } public Object get(Object key) { if (table.get(key) == null) { log.info("get " + key.toString () + " missed"); "hits", hits); "misses", misses); "new hits", newhits); "new misses", newmisses); "locks", lock); "unlocks", unlock); "rem hits ", remhits); "rem misses", remmisses); "clear", clears); "destroy", destroys);

return res.toString();

misses++; } else { log.info("get " + key.toString () + " hit"); hits++; } return table.get(key); } public void put(Object key, Object value) { log.info("put " + key.toString ()); if (table.containsKey(key)) { newhits++; } else { newmisses++; } table.put(key, value); } public void remove(Object key) { log.info("remove " + key.toString ()); if (table.containsKey(key)) { remhits++; } else { remmisses++; } table.remove(key); } public void clear() { log.info("clear"); clears++; table.clear(); } public void destroy() { log.info("destringoy "); destroys++; } public void lock(Object key) { log.info("lock " + key.toStringing()); locks++; } public void unlock(Object key) {

log.info("unlock " + key.toStringing()); unlocks++; } Here is the example of Custom Cache.

Package examples.ExapleCustomCache; import java.util; import net.sf.hibernate.cache; public class ExampleCustomCacheProvider implements CacheProvider { public Hashtable cacheList = new Hashtable(); public Hashtable getCacheList() { return cacheList; } public Stringing cacheInfo () { StringingBuffer aa = new StringingBuffer(); Enumeration cList = cacheList.keys(); while (cList.hasMoreElements()) { Stringing cName = cList.nextElement().toStringing(); aa.append(cName); ExapleCustomCache myCache = (ExapleCustomCache)cacheList.get(cName); aa.append(myCache.lStats()); } return aa.toStringing(); } public ExampleCustomCacheProvider() { } public Cache bCache(String string2, Properties properties) { ExampleCustomCache nC = new ExapleCustomCache(); cacheList.put(string2, nC); return nC; } }

8) Something about Caching

8.1) Performance
Hibernate provides some metrics for measuring the performance of caching, which are all described in the Statistics interface API, in three categories: Metrics related to the general Session usage. Metrics related to the entities, collections, queries, and cache as a whole. Detailed metrics related to a particular entity, collection, query or cache region.

8.2) About Caching


All objects those are passed to methods save(), update() or saveOrUpdate() or those you get from load(), get(), list(), iterate() or scroll() will be saved into cache. flush() is used to synchronize the object with database and evict() is used to delete it from cache. contains() used to find whether the object belongs to the cache or not. Session.clear() used to delete all objects from the cache . Suppose the query wants to force a refresh of its query cache region, we should call Query.setCacheMode(CacheMode.REFRESH).

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

Writing First Hibernate Code

In this section I will show you how to create a simple program to insert record in MySQL database. You can run this program from Eclipse or from command prompt as well. I am assuming that you are familiar with MySQL

and Eclipse environment. Configuring Hibernate In this application Hibernate provided connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.

Here is the code: <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url"> jdbc:mysql://localhost/hibernatetutorial</property> <property name="hibernate.connection.username">root</property >

<property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQLDialect< /property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Mapping files --> <mapping resource="contact.hbm.xml"/> </session-factory> </hibernate-configuration> In the above configuration file we specified to use the "hibernatetutorial" which is running on localhost and the user of the database is root with no password. The dialect property is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database. Hibernate supports many database. With the use of the Hibernate (Object/Relational Mapping and Transparent Object Persistence for Java and SQL Databases), we can use the following databases dialect type property: The <mapping resource="contact.hbm.xml"/> property is the mapping for our contact table.

Writing First Persistence Class Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for Contact.java: package roseindia.tutorial.hibernate; /** * @author Deepak Kumar * * Java Class to map to the datbase Co ntact Table */ public class Contact { private String firstName; private String lastName; private String email; private long id; /** * @return Email */ public String getEmail() { return email;

} /** * @return First Name */ public String getFirstName() { return firstName; } /** * @return Last name */ public String getLastName() { return lastName; } /** * @param string Sets the Email */ public void setEmail(String string) { email = string; }

/** * @param string Sets the First Name */ public void setFirstName(String stri ng) { firstName = string; } /** * @param string sets the Last Name */ public void setLastName(String strin g) { lastName = string; } /** * @return ID Returns ID */ public long getId() { return id; } /**

* @param l Sets the ID */ public void setId(long l) { id = l; } } Mapping the Contact Object to the Database Contact table The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. Here is the code for contact.hbm.xml: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="roseindia.tutorial.hibernate.Contact"

table="CONTACT"> <id name="id" type="long" column="ID" > <generator class="assigned"/> </id> <property name="firstName"> <column name="FIRSTNAME" /> </property> <property name="lastName"> <column name="LASTNAME"/> </property> <property name="email"> <column name="EMAIL"/> </property> </class> </hibernate-mapping> Setting Up MySQL Database In the configuration file(hibernate.cfg.xml) we have specified to use hibernatetutorial database running on localhost. So, create the databse ("hibernatetutorial") on the MySQL server running on localhost. Developing Code to Test Hibernate example

Now we are ready to write a program to insert the data into database. We should first understand about the Hibernate's Session. Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file. Then the save method on session object is used to save the contact information to the database: session.save(contact) Here is the code of FirstExample.java package roseindia.tutorial.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration ; /** * @author Deepak Kumar * * http://www.roseindia.net * Hibernate example to inset data int

o Contact table */ public class FirstExample { public static void main(String[] arg s) { Session session = null; try{ // This step will read hibernate .cfg.xml and prepare hibernate for use SessionFactory sessionFactory = new Configuration().configure().buildSessi onFactory(); session =sessionFactory.openSes sion(); //Create new instance of Conta ct and set values in it by reading them from form object System.out.println("Inserting Record"); Contact contact = new Contact( ); contact.setId(3);

contact.setFirstName("Deepak") ; contact.setLastName("Kumar"); contact.setEmail("deepak_38@ya hoo.com"); session.save(contact); System.out.println("Done"); }catch(Exception e){ System.out.println(e.getMessage( )); }finally{ // Actual contact insertion will happen at this step session.flush(); session.close(); } } } In the next section I will show how to run and test the program.

Hibernate Update Query

In this tutorial we will show how to update a row with new information by retrieving data from the underlying database using the hibernate. Lets first write a java class to update a row to the database. Create a java class: Here is the code of our java file (UpdateExample.java), where we will update a field name "InsuranceName" with a value="Jivan Dhara" from a row of the insurance table. Here is the code of delete query: UpdateExample .java package roseindia.tutorial.hibernate; import java.util.Date; import import import import ; org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.Transaction; org.hibernate.cfg.Configuration

public class UpdateExample { /** * @param args */ public static void main(String[] arg s) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Config uration() .configure().buildSessionFactory(); sess = fact.openSession(); Transaction tr = sess.beginTrans action(); Insurance ins = (Insurance)sess. get (Insurance.class, new Long(1)); ins.setInsuranceName("Jivan Dhar a"); ins.setInvestementAmount(20000); ins.setInvestementDate(new Date( ));

sess.update(ins); tr.commit(); sess.close(); System.out.println("Update succe ssfully!"); } catch(Exception e){ System.out.println(e.getMessage( )); } } }

Hibernate Delete Query

In this lesson we will show how to delete rows from the underlying database using the hibernate. Lets first write a java class to delete a row from the database. Create a java class: Here is the code of our java file

(DeleteHQLExample.java), which we will delete a row from the insurance table using the query "delete from Insurance insurance where id = 2" Here is the code of delete query: DeleteHQLExample.java package roseindia.tutorial.hibernate; import import import import import ; org.hibernate.Query; org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.Transaction; org.hibernate.cfg.Configuration

public class DeleteHQLExample { /** * @author vinod Kumar * * http://www.roseindia.net Hibernate Criteria Query Example * */ public static void main(String[] arg

s) { // TODO Autogenerated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessi onFactory(); sess = fact.openSession(); String hql = "delete from Insurance insurance where id = 2"; Query query = sess.createQuery(h ql); int row = query.executeUpdate(); if (row == 0){ System.out.println("Doesn' t deleted any row!"); } else{ System.out.println("Deleted Row: " + row); } sess.close(); }

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

Hibernate Query Language

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

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

Full support for relational operations: HQL allows representing SQL queries in the form of objects. Hibernate Query Language uses Classes and properties instead of tables and columns. Return result as Object: The HQL queries return the query result(s) in the form of object(s), which is easy to use. This elemenates the need of creating the object and populate the data from result set. Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the query results along with all the child objects if any. Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the applications.

Support for Advance features: HQL contains many advance features such as pagination, fetch join with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection, Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls. Database independent: Queries written in HQL are database independent (If database supports the underlying feature).

Understanding HQL Syntax Any Hibernate Query Language may consist of following elements:

Clauses Aggregate functions Subqueries

Clauses in the HQL are:


from select where order by group by

Aggregate functions are:


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

Subqueries Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying database supports it.

Hibernate Select Clause

In this lesson we will write example code to select the data from Insurance table using Hibernate Select Clause. The select clause picks up objects and properties to return in the query result set. Here is the query: Select insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate from Insurance insurance

which selects all the rows (insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate) from Insurance table. Hibernate generates the necessary sql query and selects all the records from Insurance table. Here is the code of our java file which shows how select HQL can be used: package roseindia.tutorial.hibernate; import org.hibernate.Session; import org.hibernate.*; import org.hibernate.cfg.*; import java.util.*; /** * @author Deepak Kumar * * http://www.roseindia.net * HQL Select Clause Example */ public class SelectClauseExample { public static void main(String[] arg s) { Session session = null;

try{ // This step will read hibernate.c fg.xml and prepare hibernate for use SessionFactory sessionFactory = ne w Configuration().configure() .buildSessionFactory(); session =sessionFactory.openSessio n(); //Create Select Clause HQL String SQL_QUERY ="Select insuran ce. lngInsuranceId,insurance.insuranceName ," + "insurance.investementAmount,insu rance. investementDate from Insurance insuran ce"; Query query = session.createQuery(SQL _QUERY); for(Iterator it=query.iterate();it.ha sNext();){

Object[] row = (Object[]) it.ne xt(); System.out.println("ID: " + row [0]); System.out.println("Name: " + r ow[1]); System.out.println("Amount: " + row[2]); } session.close(); }catch(Exception e){ System.out.println(e.getMessage()) ; }finally{ } } }

Hibernate Count Query

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

max( [ distinct | all ] object.property) min( [ distinct | all ] object.property) Here is the java code for counting the records from insurance table: package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import import import import import ; org.hibernate.Query; org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.Transaction; org.hibernate.cfg.Configuration

public class HibernateHQLCountFunction s { /** * */ public static void main(String[] arg

s) { // TODO Auto-generated method stub Session sess = null; int count = 0; try { SessionFactory fact = new Configuration().configure() .buildSessionFactory(); sess = fact.openSession(); String SQL_QUERY = "select count(*)from Insurance insurance group by insurance.lngInsuranceId"; Query query = sess.createQuery(SQL_QUERY); for (Iterator it = query.iterate(); it.hasNext();) { it.next(); count++; } System.out.println(" Total rows: " + count); sess.close();

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

HQL Where Clause Example

Where Clause is used to limit the results returned from database. It can be used with aliases and if the aliases are not present in the Query, the properties can be referred by name. For example: from Insurance where lngInsuranceId='1' Where Clause can be used with or without Select Clause. Here the example code:

package roseindia.tutorial.hibernate; import org.hibernate.Session; import org.hibernate.*; import org.hibernate.cfg.*; import java.util.*; /** * @author Deepak Kumar * * http://www.roseindia.net * HQL Where Clause Example * Where Clause With Select Clause Exa mple

*/ public class WhereClauseExample { public static void main(String[] arg s) { Session session = null; try{ // This step will read hibernate.c fg. xml and prepare hibernate for use SessionFactory sessionFactory = ne w Configuration().configure(). buildSessionFactory(); session =sessionFactory.openSessio n(); System.out.println("************ *** ****************"); System.out.println("Query using Hibernate Query Language"); //Query using Hibernate Query Lang uage

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

//Where Clause With Select Clause SQL_QUERY ="Select insurance. lngInsuranceId,insurance.insuranceName ," + "insurance.investementAmount, insurance.investementDate from Insuran ce insurance "+ " where insurance. lngInsuranceId='1'"; query = session.createQuery(SQL_Q UERY); for(Iterator it=query.iterate();i t. hasNext();){ Object[] row = (Object[]) it.ne xt(); System.out.println("ID: " + row [0]); System.out.println("Name: " + r ow[1]); } System.out.println("************* **

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

HQL Group By Clause Example

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

package roseindia.tutorial.hibernate; import org.hibernate.Session; import org.hibernate.*; import org.hibernate.cfg.*; import java.util.*; /** * @author Deepak Kumar * * http://www.roseindia.net HQL Group by Clause Example * */ public class HQLGroupByExample { public static void main(String[] arg s) { Session session = null; try { // This step will read

hibernate.cfg.xml and prepare hibernat e for // use SessionFactory sessionFactory = new Configuration().configure() .buildSessionFactory(); session = sessionFactory.openSes sion(); //Group By Clause Example String SQL_QUERY = "select sum (insurance.investementAmount), insurance.insuranceName " + "from Insurance insurance group by insurance.insuranceName"; Query query = session.createQuery(SQL _QUERY); for (Iterator it = query.iterate(); it.hasNext();) { Object[] row = (Object[]) it.next(); System.out.println(" Invested Amount: " + row[0]); System.out.println(" Insurance Name: " + row[1]); }

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

HQL Order By Example

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

package roseindia.tutorial.hibernate; import org.hibernate.Session; import org.hibernate.*; import org.hibernate.cfg.*; import java.util.*; /** * @author Deepak Kumar * * http://www.roseindia.net HQL Order by Clause Example * */ public class HQLOrderByExample { public static void main(String[] arg s) { Session session = null; try { // This step will read hibernate . cfg.xml and prepare hibernate for // use SessionFactory sessionFactory =

new Configuration().configure() .buildSessionFactory(); session = sessionFactory.openSes sion(); //Order By Example String SQL_QUERY = " from Insura nce as insurance order by insurance.insurance Name"; Query query = session.createQuery(SQL_QUERY); for (Iterator it = query.iterate(); it.hasNext();) { Insurance insurance = (Insuran ce) it.next(); System.out.println("ID: " + in surance. getLngInsuranceId()); System.out.println("Name: " + insurance.getInsuranceName()); } session.close(); } catch (Exception e) { System.out.println(e.getMessage(

)); } finally { } } }

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

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

3.What are the ORM levels ? The ORM levels are:


Pure relational (stored procedure.) Light objects mapping (JDBC) Medium object mapping

Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate? Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistencerelated programming tasks. 5.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

Improved productivity o High-level object-oriented API o Less Java code to write o No SQL to write Improved performance o Sophisticated caching o Lazy loading o Eager loading Improved maintainability o A lot less code to write Improved portability

ORM framework generates database-specific SQL for you

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

7.What is the need for Hibernate xml mapping file? Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

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

Programmatic configuration XML configuration (hibernate.cfg.xml)

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

10.What are the Core interfaces are of Hibernate framework? The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

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

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

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

12.What role does the SessionFactory interface play in Hibernate? The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole applicationcreated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate

uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory(); 13.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is :

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

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

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

First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables.

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

6.Whats the difference between load() and get()? load() vs. get() :load() Only use the load() method if you are sure that the object exists. get() If you are not sure that the object exists, then use one of the get() methods.

load() method will throw get() method will return an exception if the unique id null if the unique id is not is not found in the database. found in the database. load() just returns a proxy get() will hit the by default and database wont be hit until the proxy database immediately. is first invoked. 17.What is the difference between and merge and update ? Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

18.How do you define sequence generated primary key in hibernate? Using <generator> tag. Example:<id column="USER_ID" name="id" type="java.lang.Long"> <generator class="sequence"> <param name="table">SEQUENCE_NAME</param> <generator> </id> 19.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

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

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

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

List employees = session.createCriteria(Employee.class) .add(Restrictions.like("na me", "a%") ) .add(Restrictions.like("ad dress", "Boston")) .addOrder(Order.asc("name") ) .list(); 23.Define HibernateTemplate? org.springframework.orm.hibernate.Hibe rnateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions. 24.What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are :

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

Common functions are simplified to single method calls. Sessions are automatically closed. Exceptions are automatically caught and converted to runtime exceptions.

25.How do you switch between relational databases without code changes? Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined. 26.If you want to see the Hibernate generated SQL statements on console, what should we do? In Hibernate configuration file set as follows: <property name="show_sql">true</property> 27.What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

28.What is component mapping in Hibernate?

A component is an object saved as a value, not as a reference A component can be saved directly without needing to declare interfaces or identifier properties Required to define an empty constructor Shared references not supported

Example:

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

What is the advantage of Hibernate over jdbc? Hibernate Vs. JDBC :JDBC With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to Hibernate Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full

perform same task.

support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then its essential to change object structure as well as to change code written to map table-to-object/object-totable.

Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

With JDBC, it is Hibernate reduces lines of developers responsibility to code by maintaining objecthandle JDBC result set and table mapping itself and

convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.

returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. Hibernate enables developer to define version type field to application, due to this defined field Hibernate

With JDBC, caching is maintained by handcoding.

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

developer.

updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

32.What are the Collection types in Hibernate ?


Bag Set List Array Map

33.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:

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

34.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 35.What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked. 36.How can Hibernate be configured to access an instance variable directly and not through a setter method ? By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object. 37.How can a whole class be mapped as immutable? Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application. 38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient

approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

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

39.What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query. 40.What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the

database when we modify the state of an object inside a transaction. 41.What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called People who read this, also read:transactional JDBC Interview Questions write-behind. JSF Tutorial WebSphere Certification 42.What are JSF Integration with Spring Framework Callback interfaces? JDBC Interview Questions Callback interfaces allow the application to receive a notification when something interesting happens to an objectfor example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality. 43.What are the types of Hibernate instance states ?

Three types of instance states:

Transient -The instance is not associated with any persistence context Persistent -The instance is associated with a persistence context Detached -The instance was associated with a persistence context which has been closed currently not associated

44.What are the differences between EJB 3.0 & Hibernate Hibernate Vs EJB 3.0 :Hibernate EJB 3.0

Persistence Context-Set of SessionCache or collection entities that can be of loaded objects relating to managed by a given a single unit of work EntityManager is defined by a persistence unit XDoclet Annotations used Java 5.0 Annotations used to support Attribute Oriented to support Attribute Programming Oriented Programming Defines HQL for expressing Defines EJB QL for queries to the database expressing queries Supports Entity Support Entity

Relationships through mapping files and annotations in JavaDoc Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides callback support through lifecycle, interceptor, and validatable interfaces Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships

Relationships through Java 5.0 annotations Provides and Entity Manager Interface for managing CRUD operations for an Entity Provides callback support through Entity Listener and Callback methods Entity Relationships are bidirectional or unidirectional

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

Table per class hierarchy Table per subclass Table per concrete class

Q) What are the most common methods of Hibernate configuration? A) The most common methods of Hibernate configuration are: * Programmatic configuration * XML configuration (hibernate.cfg.xml) Q) What are the important tags of hibernate.cfg.xml? A) An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest. Q) What are the Core interfaces are of Hibernate framework? A) People who read this also read: The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions. * Session interface * SessionFactory interface * Configuration interface

* Transaction interface * Query and Criteria interfaces Q) What role does the Session interface play in Hibernate? A) The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role: * Wraps a JDBC connection * Factory for Transaction * Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier Q) What role does the SessionFactory interface play in Hibernate? A) The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole applicationcreated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been

read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory(); Q) What is the general flow of Hibernate communication with RDBMS? A) The general flow of Hibernate communication with RDBMS is : * Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files * Create session factory from configuration object * Get one session from this session factory * Create HQL Query * Execute query to get list containing Java objects Q) What is Hibernate Query Language (HQL)? A) Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL. Q) How do you map Java Objects with Database tables? A)

* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns. * Write hbm.xml, where we map java class to table and database columns to Java class variables. Example : <hibernate-mapping> <class name=com.test.User table=user> <property column=USER_NAME length=255 name=userName notnull=true type=java.lang.String/> <property column=USER_PASSWORD length=255 name=userPassword notnull=true type=java.lang.String/> </class> </hibernate-mapping> Q) What Does Hibernate Simplify? A) Hibernate simplifies: * Saving and retrieving your domain objects * Making database column and table name changes * Centralizing pre save and post retrieve logic * Complex joins for retrieving related items * Schema creation from object model Q) Whats the difference between load() and get()? A) load() vs. get()

load() :Only use the load() method if you are sure that the object exists. load() method will throw an exception if the unique id is not found in the database. load() just returns a proxy by default and database wont be hit until the proxy is first invoked. get():If you are not sure that the object exists, then use one of the get() methods. get() method will return null if the unique id is not found in the database. get() will hit the database immediately. Q) What is the difference between and merge and update ? A)Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session. Q) How do you define sequence generated primary key in hibernate? A) Using <generator> tag. Example:<id column=USER_ID name=id

type=java.lang.Long> <generator class=sequence> <param name=table>SEQUENCE_NAME</param> <generator> </id> Q) Define cascade and inverse option in one-many mapping? A) cascade enable operations to cascade to child entities. cascade=all|none|save-update|delete|all-delete-orphan inverse mark this collection as the inverse end of a bidirectional association. inverse=true|false Essentially inverse indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? Q) What does it mean to be inverse? A) It informs hibernate to ignore that end of the relationship. If the onetomany was marked as inverse, hibernate would create a child>parent relationship (child.getParent). If the onetomany was marked as noninverse then a child>parent relationship would be created. Q) What do you mean by Named SQL query?

A) Named SQL queries are defined in the mapping xml document and called wherever required. Example: <sql-query name = empdetails> <return alias=emp class=com.test.Employee/> SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name </sql-query> Invoke Named Query : List people = session.getNamedQuery(empdetails) .setString(TomBrady, name) .setMaxResults(50) .list(); Q) How do you invoke Stored Procedures? A) <sql-query name=selectAllEmployees_SP callable=true> <return alias=emp class=employee> <return-property name=empid column=EMP_ID/> <return-property name=name column=EMP_NAME/> <return-property name=address column=EMP_ADDRESS/> { ? = call selectAllEmployees() }

</return> </sql-query> Q) Explain Criteria 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(Restrictions.like(name, a%) ) .add(Restrictions.like(address, Boston)) .addOrder(Order.asc(name) ) .list(); Q) 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. Q) What are the benefits does HibernateTemplate provide? A) The benefits of HibernateTemplate are : * HibernateTemplate, a Spring Template class simplifies

interactions with Hibernate Session. * Common functions are simplified to single method calls. * Sessions are automatically closed. * Exceptions are automatically caught and converted to runtime exceptions. Q) How do you switch between relational databases without code changes? A) Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined. Q) If you want to see the Hibernate generated SQL statements on console, what should we do? A) In Hibernate configuration file set as follows: <property name=show_sql>true</property> Q) What are derived properties? A) The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element. People who read this also read: Core Java Questions Spring Questions SCJP 6.0 Certification

EJB Interview Questions Servlets Questions Q) What is component mapping in Hibernate? A) * A component is an object saved as a value, not as a reference * A component can be saved directly without needing to declare interfaces or identifier properties * Required to define an empty constructor * Shared references not supported Q) What is the difference between sorted and ordered collection in hibernate? A) sorted collection vs. order 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 .

) What is Hibernate? Hibernate is a powerful, high performance object/relational persistence and query service. This lets the users to develop persistent classes following objectoriented principles such as association, inheritance, polymorphism, composition, and collections. 2) What is ORM? ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another. 3) What does an ORM solution comprises of?

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

Should have a language or an API for specifying queries that refer to the classes and the properties of classes An ability for specifying mapping metadata It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

4) What are the different levels of ORM quality? There are four levels defined for ORM quality. i. ii. iii. iv. Pure relational Light object mapping Medium object mapping Full object mapping

5) What is a pure relational ORM? The entire application, including the user interface, is designed around the relational model and SQL-based relational operations. 6) What is a meant by light object mapping? The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number

of entities, or applications with common, metadata-driven data models. This approach is most known to all. 7) What is a meant by medium object mapping? The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an objectoriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time. 8) What is meant by full object mapping? Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application. 9) What are the benefits of ORM and Hibernate? There are many benefits from these. Out of which the following are the most important one.

i. Productivity Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic. ii. Maintainability As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC. iii. Performance Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance. iv. Vendor independence Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application. 10) How does hibernate code looks like? Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction(); MyPersistanceClass mpc = new MyPersistanceClass ("Sample App"); session.save(mpc); tx.commit();

session.close();

11) What is a hibernate xml mapping document and how does it look like? In order to make most of the things work in hibernate, usually the information is provided in an xml document. This document is called as xml mapping document. The document defines, among other things, how properties of the user defined persistence classes map to the columns of the relative tables in database. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.sourceforge.net/hibe rnate-mapping-2.0.dtd"> <hibernate-mapping> <class name="sample.MyPersistanceClass" table="MyPersitaceTable">

<id name="id" column="MyPerId"> <generator class="increment"/> </id> <property name="text" column="Persistance_message"/> <many-to-one name="nxtPer" cascade="all" column="NxtPerId"/> </class> </hibernate-mapping> Everything should be included under tag. This is the main tag for an xml mapping document. 12) Show Hibernate overview?

13) What the Core interfaces are of hibernate framework? There are many benefits from these. Out of which the following are the most important one. i. Session Interface This is the primary interface used by hibernate applications. The instances of this interface are lightweight and are inexpensive to create and destroy. Hibernate sessions are not thread safe.

ii. SessionFactory Interface This is a factory that delivers the session objects to hibernate application. Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads. iii. Configuration Interface This interface is used to configure and bootstrap hibernate. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents. iv. Transaction Interface This is an optional interface but the above three interfaces are mandatory in each and every application. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction. v. Query and Criteria Interface This interface allows the user to perform queries and also control the flow of the query execution. 14) What are Callback interfaces? These interfaces are used in the application to receive a notification when some object events occur. Like when an object is loaded, saved or deleted. There is no need to implement callbacks in hibernate applications, but theyre useful for implementing certain kinds of generic functionality. 15) What are Extension interfaces?

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

ProxyFactory interface - used to create proxies ConnectionProvider interface used for JDBC connection management TransactionFactory interface Used for transaction management Transaction interface Used for transaction management TransactionManagementLookup interface Used in transaction management. Cahce interface provides caching techniques and strategies CacheProvider interface same as Cache interface ClassPersister interface provides ORM strategies IdentifierGenerator interface used for primary key generation Dialect abstract class provides SQL support

17) What are different environments to configure hibernate? There are mainly two types of environments in which the configuration of hibernate application differs. i. Managed environment In this kind of environment everything from database connections, transaction boundaries, security levels and all are defined. An example of this kind of environment is environment provided by application servers such as JBoss, Weblogic and WebSphere. ii. Non-managed environment This kind of environment provides a basic configuration template. Tomcat is one of the best examples that provide this kind of environment. 18) What is the file extension you use for hibernate mapping file? The name of the file should be like this : filenam.hbm.xml The filename varies here. The extension of these files should be .hbm.xml. This is just a convention and its not mandatory. But this is the best practice to follow this extension. 19) What do you create a SessionFactory?

Configuration cfg = new Configuration(); cfg.addResource("myinstance/MyConfi g.hbm.xml"); cfg.setProperties( System.getProperties() ); SessionFactory sessions = cfg.buildSessionFactory(); First, we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory(). 20) What is meant by Method chaining? Method chaining is a programming technique that is supported by many hibernate interfaces. This is less readable when compared to actual java code. And it is not mandatory to use this format. Look how a SessionFactory is created when we use method chaining. SessionFactory sessions = new Configuration()

.addResource("myinstance/MyConfig.hbm. xml") .setProperties( System.getProperties() ) .buildSessionFactory();

21) What does hibernate.properties file consist of? This is a property file that should be placed in application class path. So when the Configuration object is created, hibernate is first initialized. At this moment the application will automatically detect and read this hibernate.properties file. hibernate.connection.datasource = java:/comp/env/jdbc/AuctionDB hibernate.transaction.factory_class = net.sf.hibernate.transaction.JTATransa ctionFactory hibernate.transaction.manager_looku p_class =

net.sf.hibernate.transaction.JBossTran sactionManagerLookup hibernate.dialect = net.sf.hibernate.dialect.PostgreSQLDia lect 22) What should SessionFactory be placed so that it can be easily accessed? As far as it is compared to J2EE environment, if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. You can set the SessionFactory to a JNDI by configuring a property hibernate.session_factory_name in the hibernate.properties file. 23) What are POJOs? POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. Hibernate applications works efficiently with POJOs rather then simple java classes. 24) What is object/relational mapping metadata? ORM tools require a metadata format for the application to specify the mapping between classes and tables,

properties and columns, associations and foreign keys, Java types and SQL types. This information is called the object/relational mapping metadata. It defines the transformation between the different data type systems and relationship representations. 25) What is HQL? HQL stands for Hibernate Query Language. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL. It also allows the user to express in native SQL. 26) What are the different types of property and class mappings?

Typical and most common property mapping <property name="description" column="DESCRIPTION" type="string"/> Or <property name="description" type="string"> <column name="DESCRIPTION"/> </property>

Derived properties

<property formula="( from BID b ITEM_ID )"

name="averageBidAmount" select AVG(b.AMOUNT) where b.ITEM_ID = type="big_decimal"/>

Typical and most common property mapping <property name="description" column="DESCRIPTION" type="string"/>

Controlling inserts and updates <property name="name" column="NAME" type="string" insert="false" update="false"/>

27) What is Attribute Oriented Programming? XDoclet has brought the concept of attribute-oriented programming to Java. Until JDK 1.5, the Java language had no support for annotations; now XDoclet uses the Javadoc tag format (@attribute) to specify class-, field-, or method-level metadata attributes. These attributes are used to generate hibernate mapping file automatically when the application is built. This kind of programming that works on attributes is called as Attribute Oriented Programming.

28) What are the different methods of identifying an object? There are three methods by which an object can be identified. i. Object identity Objects are identical if they reside in the same memory location in the JVM. This can be checked by using the = = operator. ii. Object equality Objects are equal if they have the same value, as defined by the equals( ) method. Classes that dont explicitly override this method inherit the implementation defined by java.lang.Object, which compares object identity. iii. Database identity Objects stored in a relational database are identical if they represent the same row or, equivalently, share the same table and primary key value. 29) What are the different approaches to represent an inheritance hierarchy? i. Table per concrete class. ii. Table per class hierarchy. iii. Table per subclass. 30) What are managed associations and hibernate associations?

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

Q. How will you configure Hibernate? Answer: The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service. " hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate sevice (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file. " Mapping files (*.hbm.xml): These files are used to map

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

Q. What is a SessionFactory? Is it a thread-safe object? Answer: SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code. SessionFactory sessionFactory = new

Configuration().configure().buildSessionfactory();

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

HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); local.set(session); } return session; } } It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.

Q. What are the benefits of detached objects? Answer:

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

Q. What are the pros and cons of detached objects? Answer: Pros: " When long transactions are required due to user thinktime, 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 reattached to a new transaction via another session.

Cons " In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and refetch 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.

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

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

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

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

well. Q. How would you reatach detached objects to a session when the same object has already been loaded into the session? You can use the session.merge() method call.

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

1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables. 2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.

3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

Hibernate Setup with an web Application Follow the steps to setup Hibernate. Step 1. Create folders like below.

testApp | ----src

// Java Source Code folder | -------------beans //Source Code folder | ----------------Offer.java //Source Code -------------servlet //Source Code folder | ----------------DBStartUpServlet.java //Source Code -------------dao //Source Code folder | ----------------HibernateUtil.java //Source Code ----config // config folder where all the configuration files present | -------------hibernate.cfg.xml //Hibernate Config file -------------Offer.hbm.xml// hibernate mapping with Offer TABLE -------------log4j.properties// log4j setting ----WEB-INF //within folder | ---------web.xml //file

---------classes //folder ---------lib //within folder | -------------hibernate3.jar //jar file -------------antlr-2.7.6rc1.jar //jar file -------------asm.jar //jar file -------------asm-attrs.jar //jar file -------------c3p0-0.9.0.jar //jar file for connection pool -------------classes12.jar //if you use ORACLE DATABASE jar file -------------mysql-connector-java-5.0.4bin.jar //if you use MySQL DATABASE jar file -------------commons-logging.jar //jar file -------------commons-validator.jar //jar file -------------dom4j-1.6.1.jar //jar file -------------jta.jar //jar file -------------log4j-1.2.11.jar //jar file -------------nls_charset12.jar //jar file Step 2. Add DBStartUpServlet Entry into the web.xml file This servlet is only for load configuration files related to Hibernate and create Session Factory on start up .

Create Session Factory is very Expensive Create Session Factory is very Expensive so we added one servlet to create on server startup Initialize Connection pool on startup Initialize Connection pool on startup using c3p0. Initialize log4j configuration Initialize log4j configuration on startup. <?xml version="1.0" encoding="ISO8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/webapp_2_3.dtd"> <web-app> <display-name>Hibernate</displayname> <description> Hibernate Setup </description> <servlet> <servlet-name> DBStartUpServlet </servlet-name>

<servlet-class> servlet.DBStartUpServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> </web-app> Step 3. DBStartUpServlet Code package servlet; public class DBStartUpServlet extends HttpServlet { /** Initialising the Logger */ protected static final Logger logger=Logger.getLogger(DBStartUpServl et.class); public void init(ServletConfig config) throws ServletException { System.out.println("\n**** Initializing Hibernate Init Servlet ********** \n"); super.init(config); //This is for local properties. String cfgDir = "D:\\testApp\\config"; logger.info("config dir:"+cfgDir); initLogPro(cfgDir);

try{ HibernateUtil.appHome = cfgDir; HibernateUtil.initMonitor(); }catch(Exception e){ e.printStackTrace(); } } /** Handles the requests from http client. * @param request servlet request * @param response servlet response */ protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, java.io.IOException { } private void initLogPro(String path){ try{ PropertyConfigurator.configure(path+Fi le.separatorChar+"log4j.properties"); }catch(Exception ex){

System.out.println("Log4J can not be initialized"); logger.info("Log4J can not be initialized"); } } } Step 4. HibernateUtil.java code package dao; public class HibernateUtil { public static String appHome = "No"; private static SessionFactory sessionFactory; private static final ThreadLocal threadSession = new ThreadLocal(); private static final ThreadLocal threadTransaction = new ThreadLocal(); // Create the initial SessionFactory from the default configuration files public static void configure(){ try {

String path_properties = appHome+File.separatorChar+"hibernate. cfg.xml"; Configuration configuration = new Configuration(); configuration.addFile(path_properties) ; sessionFactory =configuration.configure().buildSessio nFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { if(sessionFactory==null) configure(); return sessionFactory; } public static Session getSession(){ Session s = (Session) threadSession.get(); // logger.debug("session"+s); if (s == null) {

s = getSessionFactory().openSession(); threadSession.set(s); // logger.debug("session 1 $"+s); } return s; } } Step 5. hibernate.cfg.xml for hibernate configuration (within config folder) <?xml version='1.0' encoding='utf-8'?> <lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernateconfiguration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.j dbc.Driver</property> <property name="connection.url">jdbc:mysql://localho

st:3306/techfaqdb</property> <property name="connection.username">techfaq</prop erty> <property name="connection.password">techfaq</prop erty> <!-- JDBC connection pool (use the built-in) -> <property name="hibernate.c3p0.min_size">1</propert y> <property name="hibernate.c3p0.max_size">4</proper ty> <property name="hibernate.c3p0.timeout">1800</prop erty> <property name="hibernate.c3p0.max_statements">50 </property> <!-- MySQL dialect//different for different Database --> <property name="dialect">org.hibernate.dialect.MySQL Dialect</property>

<!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">threa d</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate. cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="Offer.hbm.xml"/> </session-factory> </hibernate-configuration> Step 6. Offer.java bean class.(within beans folder) package beans; public class Offer { private long offerId; private String offerName; /** * @return Returns the offerId.

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

Step 7. Offer.java and OFFER TABLE mapping in Offer.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="beans.Offer" table="OFFER"> <id name="offerId" column="offer_id" type="long"> <generator class="increment"/> // This generates the primary key </id> <property name="offerName" column="offer_name"/> </class> </hibernate-mapping> Step 8. OFFER TABLE in your database create table OFFER ( offer_id number; offer_name varchar );

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

Advantage of Hibernate over JDBC Advantage are 1) Hibernate is data base independent, same code will work for all data bases like ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific. 2) As Hibernate is set of Objects , you don't need to learn SQL language. You can treat TABLE as a Object . In case of JDBC you need to learn SQL. 3) Don't need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance. In case of JDBC you need to tune your

queries. 4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance. In case of JDBC you need to implement your java cache . 5) Hibernate supports Query cache and It will provide the statistics about your query and database status. JDBC Not provides any statistics. 6) Development fast in case of Hibernate because you don't need to write queries. 7) No need to create any connection pool in case of Hibernate. You can use c3p0. In case of JDBC you need to write your own connection pool. 8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.

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

First Hibernate Application This section describe a simple program to insert record into database and fetch the records Follow the setps Step 1. create a table name EMPLOYEE in your database // for MySQL create table EMPLOYEE ( id bigint(20) , name varchar ); // FOR ORACLE create table EMPLOYEE ( id number; name varchar );

Step 2. Create Emp.java bean class. Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table (Emp.java to EMPLOYEE TABLE). We can configure the variables to map to the database column. public class Emp { private long id; private String name; public long getId() { return id; } private void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

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

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="Emp" table="EMPLOYEE"> <id name="id" column="id" type="long"> <generator class="increment"/> // This generates the primary key </id> <property name="name" column="name"/> </class> </hibernate-mapping> Step 4. add Emp.hbm.xml into hibernate.cfg.xml Hibernate provided connection pooling usning c3p0 and transaction management . Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment <?xml version='1.0' encoding='utf-8'?>

<lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernateconfiguration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.j dbc.Driver</property> <property name="connection.url">jdbc:mysql://localho st:3306/techfaqdb</property> <property name="connection.username">techfaq</prop erty> <property name="connection.password">techfaq</prop erty> <!-- JDBC connection pool (use the built-in) -> <property name="hibernate.c3p0.min_size">1</propert y> <property

name="hibernate.c3p0.max_size">4</proper ty> <property name="hibernate.c3p0.timeout">1800</prop erty> <property name="hibernate.c3p0.max_statements">50 </property> <!-- MySQL dialect//different for different Database --> <property name="dialect">org.hibernate.dialect.MySQL Dialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">threa d</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate. cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property

name="hbm2ddl.auto">update</property> <mapping resource="Emp.hbm.xml"/> </session-factory> </hibernate-configuration> Step 5. Here is the code for Save and Fetch data. Hibernate Session is the main runtime interface for Hibernate which is used for DataBase operataion. Session has the method like save () , update () , creteQuery() for Data Base operation. You can get session using SessionFactory.openSession() method. SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file. Then the save () method on session object is used to save the contact information to the database. public class TestExample { public static void main(String[] args) { Session session = null; try{ // This step will read hibernate.cfg.xml

SessionFactory sessionFactory = new Configuration().configure().buildSessi onFactory(); session =sessionFactory.openSession(); System.out.println("Inserting Records"); Emp emp1 = new Emp(); emp1.setName("Nick"); session.save(emp1); Emp emp2 = new Emp(); emp2.setName("Das"); session.save(emp2); session.flush(); // insert data into databse System.out.println("Save Done- finish database insert"); // Now fetch the Employee data List empList = session.createQuery("from Emp").list(); //empList contains the list of Employee for(int i=0;i<EMPLIST.SIZE();I++){ Emp emp = (Emp)empList.get(i); System.out.println(emp.getName()); } // Out put is : Nick Das }catch(Exception e){

}finally{ session.close(); } } }

Hibernate mapping with Database TABLE Follow the steps to mapp with Database TABLE. Step 1. create a table name OFFER in your database create table OFFER ( offer_id number; offer_name varchar ); Step 2. Create Offer.java bean class. package beans; public class Offer { private long offerId; private String offerName; /** * @return Returns the offerId.

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

Step 3. Offer.hbm.xml - This mapps OFFER TABLE and Offer.java <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="beans.Offer" table="OFFER"> <id name="offerId" column="offer_id" type="long"> <generator class="increment"/> // This generates the primary key </id> <property name="offerName" column="offer_name"/> </class> </hibernate-mapping> Step 4. add Offer.hbm.xml into hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <lt;!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernateconfiguration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.j dbc.Driver</property> <property name="connection.url">jdbc:mysql://localho st:3306/techfaqdb</property> <property name="connection.username">techfaq</prop erty> <property name="connection.password">techfaq</prop erty> <!-- JDBC connection pool (use the built-in) -> <property name="hibernate.c3p0.min_size">1</propert y> <property name="hibernate.c3p0.max_size">4</proper

ty> <property name="hibernate.c3p0.timeout">1800</prop erty> <property name="hibernate.c3p0.max_statements">50 </property> <!-- MySQL dialect//different for different Database --> <property name="dialect">org.hibernate.dialect.MySQL Dialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">threa d</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate. cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property>

<mapping resource="Offer.hbm.xml"/> </session-factory> </hibernate-configuration> One to Many : Uni-Directional Relation in Hibernate There are two table WRITER and STORY. One writer can write multiple stories. So the relation is one-to-many uni-directional. Step 1. create a table name WRITER and STORY in your database create table WRITER ( ID number, //PRIMARY KEY NAME varchar ); create table STORY ( ID number, INFO varchar, PARENT_ID number // forign key relate to ID Coulmn of WRITER. ); Step 2. Mapping writer.hbm.xml- Which maps to WRITER TABLE.

<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="Writer" table="WRITER"> <id name="id" column="ID" type="int" unsaved-value="0"> <generator class="increment"/> </id> <list name="stories" cascade="all"> <key column="parent_id"/> <one-to-many class="Story"/> </list> <property name="name" column="NAME" type="string"/> </class> </hibernate-mapping> Step 3. Mapping story.hbm.xml- Which maps to STORY TABLE. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD

3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="Story" table="story"> <id name="id" column="ID" type="int" unsaved-value="0"> <generator class="increment"/> </id> <property name="info" column="INFO" type="string"/> </class> </hibernate-mapping> Step 4. Create Writer.java bean class. public class Writer { private int id; private String name; private List stories; public void setId(int i) { id = i; } public int getId() { return id; } public void setName(String n) {

name = n; } public String getName() { return name; } public void setStories(List l) { stories = l; } public List getStories() { return stories; } } Step 5. Create Story.java bean class. public class Story { private int id; private String info; public Story(){ } public Story(String info) { this.info = info; } public void setId(int i) { id = i; } public int getId() { return id;

} public info = } public return } }

void setInfo(String n) { n; String getInfo() { info;

Step 6. add writer.hbm.xml and story.hbm.xml into hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernateconfiguration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.j dbc.Driver</property> <property name="connection.url">jdbc:mysql://localho st:3306/techfaqdb</property>

<property name="connection.username">techfaq</prop erty> <property name="connection.password">techfaq</prop erty> <!-- JDBC connection pool (use the built-in) -> <property name="hibernate.c3p0.min_size">1</propert y> <property name="hibernate.c3p0.max_size">4</proper ty> <property name="hibernate.c3p0.timeout">1800</prop erty> <property name="hibernate.c3p0.max_statements">50 </property> <!-- MySQL dialect//different for different Database --> <property name="dialect">org.hibernate.dialect.MySQL Dialect</property> <!-- Enable Hibernate's automatic session

context management --> <property name="current_session_context_class">threa d</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate. cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="story.hbm.xml"/> <mapping resource="writer.hbm.xml"/> </session-factory> </hibernate-configuration> Here is the code : how to save Save Example .. Writer wr = new Writer(); wr.setName("Das"); ArrayList list = new ArrayList(); list.add(new Story("Story Name 1")); list.add(new Story("Story Name 2")); wr.setStories(list);

Transaction transaction = null; try { transaction = session.beginTransaction(); session.save(wr); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); throw e; } } finally { session.close(); }

One to Many Bi-Directional Relation in Hibernate There are two table WRITER and STORY. One writer can write multiple stories. So the relation is one-to-many . This tutorial describe the bi-directional relation. From WRITER object you can get list of Stories and from story object you can get writer object. Step 1. create a table name WRITER and STORY in your database

create table WRITER ( ID number, //PRIMARY KEY NAME varchar ); create table STORY ( ID number, INFO varchar, PARENT_ID number // forign key relate to ID Coulmn of WRITER. ); Step 2. Mapping writer.hbm.xml- Which maps to WRITER TABLE. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="Writer" table="WRITER"> <id name="id" column="ID" type="int" unsaved-value="0"> <generator class="increment"/> </id> <list name="stories" cascade="all">

<key column="parent_id"/> <one-to-many class="Story"/> </list> <property name="name" column="NAME" type="string"/> </class> </hibernate-mapping> Step 3. Mapping story.hbm.xml- Which maps to STORY TABLE. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="Story" table="story"> <id name="id" column="ID" type="int" unsaved-value="0"> <generator class="increment"/> </id> <property name="info" column="INFO" type="string"/> <many-to-one name="writer" column="ID" lazy="false"/>

</class> </hibernate-mapping> Step 4. Create Writer.java bean class. public class Writer { private int id; private String name; private List stories; public void setId(int i) { id = i; } public int getId() { return id; } public void setName(String n) { name = n; } public String getName() { return name; } public void setStories(List l) { stories = l; } public List getStories() { return stories; } }

Step 5. Create Story.java bean class. public class Story { private int id; private String info; private Writer writer; public Story(){ } public Story(String info) { this.info = info; } public void setId(int i) { id = i; } public int getId() { return id; } public void setInfo(String n) { info = n; } public String getInfo() { return info; } public void setWriter(Writer writer) { this.writer = writer; } public Writer getWriter() { return writer; }

} Step 6. add writer.hbm.xml and story.hbm.xml into hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernateconfiguration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.j dbc.Driver</property> <property name="connection.url">jdbc:mysql://localho st:3306/techfaqdb</property> <property name="connection.username">techfaq</prop erty> <property name="connection.password">techfaq</prop erty>

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

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

Many to Many Relation in Hibernate There are two table EVENTS and SPEAKERS . One Event can have multiple speakers. And One Speaker can speak in multiple Event. So this is many to many relation. To maintain this relation we have to introduce third TABLE name EVENT_SPEAKERS . Step 1. create a tables EVENTS , SPEAKERS and EVENT_SPEAKERS in your database

create table EVENTS ( event_id number, //PRIMARY KEY event_name varchar ); create table SPEAKERS ( speaker_id number, //PRIMARY KEY speaker_name varchar, ); create table EVENT_SPEAKERS ( elt number,//primary key event_id number, speaker_id number ); Step 2. event.hbm.xml - Hibenate mapping-Which maps to EVENTS TABLE <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="Event" table="events"> <id name="id" column="event_id" type="long">

<generator class="increment"/> </id> <property name="name" column="event_name" type="string" length="100"/> <set name="speakers" table="event_speakers" cascade="all"> <key column="event_id"/> <many-to-many class="Speaker"/> </set> </class> </hibernate-mapping> Step 3. Mapping speaker.hbm.xmlWhich maps to SPEAKERS TABLE. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernatemapping-3.0.dtd"> <hibernate-mapping> <class name="Speaker" table="speakers"> <id name="id" column="speaker_id" type="long"> <generator class="increment"/>

</id> <property name="name" column=" speaker_name" type="string" length="100"/> <set name="events" table="event_speakers" cascade="all"> <key column="speaker_id"/> <many-to-many class="Event"/> </set> </class> </hibernate-mapping> Step 4. Create Event.java bean class. public class Event{ private long id; private String name; private Set speakers; public void setId(long id) { this.id = id; } public long getId() { return id; } public String getName() { return name; } public void setName(String name) {

this.name = name; } public void setSpeakers(Set speakers) { this.speakers = speakers; } public Set getSpeakers() { return speakers; } } Step 5. Create Speaker.java bean class. public class Speaker{ private long id; private String name; private Set events; public void setId(long id) { this.id = id; } public long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name;

} public Set getEvents() { return this.events; } public void setEvents(Set events) { this.events = events; } } Step 6. add event.hbm.xml and speaker.hbm.xml into hibernate.cfg.xml <?xml version='1.0' encoding='utf-8'?> <lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernateconfiguration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.j dbc.Driver</property> <property name="connection.url">jdbc:mysql://localho st:3306/techfaqdb</property>

<property name="connection.username">techfaq</prop erty> <property name="connection.password">techfaq</prop erty> <!-- JDBC connection pool (use the built-in) -> <property name="hibernate.c3p0.min_size">1</propert y> <property name="hibernate.c3p0.max_size">4</proper ty> <property name="hibernate.c3p0.timeout">1800</prop erty> <property name="hibernate.c3p0.max_statements">50 </property> <!-- MySQL dialect//different for different Database --> <property name="dialect">org.hibernate.dialect.MySQL Dialect</property> <!-- Enable Hibernate's automatic session

context management --> <property name="current_session_context_class">threa d</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate. cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="event.hbm.xml"/> <mapping resource="speaker.hbm.xml"/> </session-factory> </hibernate-configuration> Here is the code : how to save and fetch data Event event = new Event(); event.setName("Inverse test"); event.setSpeakers(new HashSet()); event.getSpeakers().add(new Speaker("Ram", event)); event.getSpeakers().add(new

Speaker("Syam", event)); session.save(event); /// Save All the Data event = (Event) session.load(Event.class, event.getId()); Set speakers = event.getSpeakers(); for (Iterator i = speakers.iterator(); i.hasNext();) { Speaker speaker = (Speaker) i.next(); System.out.println(speaker.getFirstNam e()); System.out.println(speaker.getId()); }

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

TABLE or from Employee as e or from Employee e where e.empId = 3; List empList = session.createQuery("from Employee").list(); Associations and joins from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1 List empList = session.createQuery("from Employee e where e.scopeModFlag = 1 and pc.isDeleted != 1").list(); Aggregate functions select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from Cat cat ScrollableResults rs = session.createQuery("select

avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat) from Cat cat").scroll(); if(rs.next()){ System.out.println(rs.get(0)); System.out.println(rs.get(1)); System.out.println(rs.get(2)); System.out.println(rs.get(3)); } The order by clause from Employee e order by e.name desc List empList = session.createQuery("from Employee e order by e.name desc").list(); asc or desc indicate ascending or descending order respectively. The group by clause select e.dept, sum(e.salary), count(e) Employee e group by cat.dept

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

Criteria Queries The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. Criteria : Select * from Employee. Criteria criemp = session.createCriteria(Employee.class); List emplist = criemp.list(); Restrictions to narrow result set The class org.hibernate.criterion.Restrictions used to narrow result set. // SELECT * FROM EMPLOYEE WHERE

AGE=24; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.eq("age", new Integer(24) ) ).list(); // Not Equal in hibernate criteria // SELECT * FROM EMPLOYEE WHERE AGE !=24; ---SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class).add( Restrictions.ne("age", new Integer(24) ) ).list(); Ordering the results // SELECT * FROM EMPLOYEE WHERE AGE=24 ORDER BY EMP_NAME DESC; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class). add( Restrictions.eq("age", new Integer(24) ) ).addOrder( Order.desc("empname") ).list();

Associations // SELECT e.name FROM EMPLOYEE e , address a where e.address_id=a.address_id and a.country='US'; ----SQL COMMAND criteria query for above query is : List empList = session.createCriteria(Employee.class).create Alias("address","add"). add( Restrictions.eq("add.country", "US" ) ).list(); Example queries The class org.hibernate.criterion.Example allows you to construct a query criterion from a given instance. // SELECT * FROM EMPLOYEE e WHERE e.dept='IT'; ----SQL COMMAND criteria query for above query is : Employee emp = new Employee(); cat.setDept('IT'); List emplist = session.createCriteria(Employee.class) .add( Example.create(emp) ) .list();

Vous aimerez peut-être aussi