Top Banner
What is Hibernate? Hibernate 3.0, the latest Open Source persistence technology at the heart of J2EE EJB 3.0 is available for download from Hibernet.org .The Hibernate 3.0 core is 68,549 lines of Java code together with 27,948 lines of unit tests, all freely available under the LGPL, and has been in development for well over a year. Hibernate maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduces the development time. Hibernate is not the best solutions for data centric applications that only uses the stored-procedures to implement the business logic in database. It is most useful with object- oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows transparent persistence that enables the applications to switch any database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans. Features of Hibernate Hibernate 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database. Filters for working with temporal (historical), regional or permissioned data. Enhanced Criteria query API: with full support for projection/aggregation and subselects. Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser. Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0, including mapping editor, interactive query prototyping, schema reverse engineering tool. Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free. Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the clustered environments. Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework. Automatic Key Generation: Hibernate supports the automatic generation of primary key for your. JDK 1.5 Enhancements: The new JDK has been released as a preview earlier this year and we expect a slow migration to the new 1.5 platform throughout 2004. While Hibernate3 still runs perfectly with JDK 1.2, Hibernate3 will make use of some
40
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Hibernate

What is Hibernate?Hibernate 3.0, the latest Open Source persistence technology at the heart of J2EE EJB 3.0 is available for download from Hibernet.org.The Hibernate 3.0 core is 68,549 lines of Java code together with 27,948 lines of unit tests, all freely available under the LGPL, and has been in development for well over a year. Hibernate maps the Java classes to the database tables. It also provides the data query and retrieval facilities that significantly reduces the development time.  Hibernate is not the best solutions for data centric applications that only uses the stored-procedures to implement the business logic in database. It is most useful with object-oriented domain modes and business logic in the Java-based middle-tier. Hibernate allows transparent persistence that enables the applications to switch any database. Hibernate can be used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans. Features of HibernateHibernate 3.0 provides three full-featured query facilities: Hibernate Query Language, the newly enhanced Hibernate Criteria Query API, and enhanced support for queries expressed in the native SQL dialect of the database.Filters for working with temporal (historical), regional or permissioned data. Enhanced Criteria query API: with full support for projection/aggregation and subselects.   Runtime performance monitoring: via JMX or local Java API, including a second-level cache browser.   Eclipse support, including a suite of Eclipse plug-ins for working with Hibernate 3.0, including mapping editor, interactive query prototyping, schema reverse engineering tool.    Hibernate is Free under LGPL: Hibernate can be used to develop/package and distribute the applications for free.    Hibernate is Scalable: Hibernate is very performant and due to its dual-layer architecture can be used in the clustered environments.   Less Development Time: Hibernate reduces the development timings as it supports inheritance, polymorphism, composition and the Java Collection framework.   Automatic Key Generation: Hibernate supports the automatic generation of primary key for your.JDK 1.5 Enhancements: The new JDK has been released as a preview earlier this year and we expect a slow migration to the new 1.5 platform throughout 2004. While Hibernate3 still runs perfectly with JDK 1.2, Hibernate3 will make use of some new JDK features. JSR 175 annotations, for example, are a perfect fit for Hibernate metadata and we will embrace them aggressively. We will also support Java generics, which basically boils down to allowing type safe collections. EJB3-style persistence operations: EJB3 defines the create() and merge() operations, which are slightly different to Hibernate's saveOrUpdate() and saveOrUpdateCopy() operations. Hibernate3 will support all four operations as methods of the Session interface. Hibernate XML binding enables data to be represented as XML and POJOs interchangeably. The EJB3 draft specification support for POJO persistence and annotations. The below diagram shows that Hibernate is using the database and configuration data to provide persistence services (and persistent objects) to the application

Page 2: Hibernate

Hibernate architecture has three main components:Connection ManagementHibernate Connection management service provide efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources of open and close the database connection.Transaction management:Transaction management service provide the ability to the user to execute more than one database statements at a time.Object relational mapping:Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query. Hibernate is very good tool as far as object relational mapping is concern, but in terms of connection management and transaction management, it is lacking in performance and capabilities. So usually hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate.Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only uses the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.ORM - Object Relation Mapping. Almost all contemporary databases are relational and based on SQL language. Most programs using them are created in an object way. So some kind of incoherence appears at the meeting point of a database and software. We need some appropriate tools to translate data from relational language into an object language and the other way round. Service of JDBC is extremely troublesome while dealing with more complex applications.ORM deals with following tasks:Hibernate is currently one of the most popular ORM solutions.Its popularity and effectiveness were proved by the fact that e.g. implementation of CMP in EJB3 on JBoss server is based on Hibernate. What is more, a lot of solutions were copied during designing EJB3 specification. Other, common solutions ORM include: CMP, JDO. Hibernate, as opposed to them, is not a standard but a concrete solution.Its main advantage is:- lightness it is no need to use special containers, it is enough to attach an appropriate �library. One can also use it to both: web and client applications. There is no need to generate manually an additional code. As opposed to e.g. JDO, Hibernate requires only presence of configuration files. Additional classes used by it are generated during performing a task. What is a persistence?Meaning of the persistence is one of the most imporant thing in application development. Nowdays almost all applications require persistent data so it is very important for an system to preserve data entered by users even if the machine was powered off. Persistance in Java ( Hibernate ) is storing data in a relational databse using SQL. Relational technology provides

Page 3: Hibernate

a way of sharing data among different aplications or among technologies that form part of the same application. Relational technology is a common denominator of many different technology platforms and systems so it is't specific to a particular application.Persistent classesNot only does Hibernate enable a programmer to gain an independence from a given database but it can also manage a state of persistent objects. A programmer may not be aware when and which queries are performed to a database.Objects of classes mapped by Hibernate may appear in three states:Transient - we create objects in this state by means of new. This kind of object is not connected with any session of Hibernate. It is a normal Java object and can be changed into Persistent - these kinds of objects are connected with both: data in a database and a given object of Session class. Hibernate detects changes in them and put them to a database at the end of a session.Detached - an object is in this state if it used to be Persistent but an appropriate session was closed. Later, it may be connected with other session. Creating, saving and loading objects.Almost each Java class may be mapped by Hibernate.It cannot be finished - it is because of the architecture which overloads persistent classes.It should have an identifier - Hibernate uses it to test equality.It must have a default constructor.Mapped fields must be public or have appropriate get/set methods.It is a common practice to use classes with JavaBean pattern (i.e. those having appropriate get/set methods for given fields) as persistent classes.Subtypes and association problemsThe problem of subtypesLet us imagine a given situation: User class is connected with BillingDetails. During performing on class object BillingDetails an instance of one of the subclasses of this class can be ascribed. Therefore the User object will actually refer to an object from different class than BillingDetails. It is a quite common way of conduct as far as an object programming is concerned. We would like to have a similar opportunity while dealing with databases, however, it is not possible that any field in a table (here: a foreign key) may refer to some fields in a few different tables. That is why while saving similar situations in a database we have to choose another solution.The problem of associationThe following situation can happen in Java: While mapping this kind of situation to a database we have to bear in mind that we cannot directly save many-to-many paradigm and we have to create an intermediate table. Hibernate (like other similar technologies, e.g. JDO, Entity Beans) meets our expectations. Hibernate becomes an additional layer in our application, a bridge between the logic of an application and a database (object/relational mapping). It enables us to define objects storing data ( as typical Java class), which can be used in our application and which are mapped to a database in a definite way. Hibernate provides us also with its own query language, structurally very similar to SQL. Both these facts make an application using Hibernate more portable.Understanding Hibernate O/R Mapping

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>  <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">   <id name="id" type="long" column="ID" >   <generator class="assigned"/>  </id>

Page 4: Hibernate

  <property name="firstName">     <column name="FIRSTNAME" />  </property>  <property name="lastName">    <column name="LASTNAME"/>  </property>  <property name="email">    <column name="EMAIL"/>  </property> </class></hibernate-mapping>

Hibernate mapping documents are simple xml documents. Here are important elements of the mapping file:.<hibernate-mapping> elementThe first or root element of hibernate mapping document is <hibernate-mapping> element. Between the <hibernate-mapping> tag class element(s) are present.   <class> elementThe <Class> element maps the class object with corresponding entity in the database. It also tells what table in the database has to access and what column in that table it should use. Within one <hibernate-mapping> element, several <class> mappings are possible.    <id> elementThe <id> element in unique identifier to identify and object. In fact <id> element map with the primary key of the table. In our code :<id name="id" type="long" column="ID" >primary key maps to the ID field of the table CONTACT. The attributes of the “id” element are: name: The property name used by the persistent class. column: The column used to store the primary key value. type: The Java data type used. unsaved-value: This is the value used to determine if a class has been made persistent. If the value of the id attribute is null, then it means that this object has not been persisted.<generator> elementThe <generator> method is used to generate the primary key for the new record. Here is some of the commonly used generators :   * Increment - This is used to generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.   *  Sequence - Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.  * Assigned - Assigned method is used when application code generates the primary key.     <property> elementThe property elements define standard Java attributes and their mapping into database schema. The property element supports the column child element to specify additional properties, such as the index name on a column or a specific column type. The <generator> elementThis is the optional element under <id> element. The <generator> element is used to specify the class name to be used to generate the primary key for new record while saving a new record. The <param> element is used to pass the parameter (s) to the  class. Here is the example of generator element from our first application:<generator class="assigned"/>In this case <generator> element do not generate the primary key and it is required to set the primary key value before calling save() method.Here are the list of some commonly used generators in hibernate:

Generator Description

incrementIt generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.

Page 5: Hibernate

identityIt supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequenceThe sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.

seqhiloThe seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuidThe uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.

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

nativeIt picks identity, sequence or hilo depending upon the capabilities of the underlying database.

assignedlets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.

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

foreignuses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

Create Table in the mysql database:User the following sql statement to create a new table in the database. CREATE TABLE `book` ( `id` int(11) NOT NULL default '0', `bookname` varchar(50) default NULL, PRIMARY KEY (`id`) ) TYPE=MyISAM Developing POJO Class (Book.java)Book.java is our POJO class which is to be persisted to the database table "book". package roseindia.tutorial.hibernate;public class Book { private long lngBookId; private String strBookName; /** * @return Returns the lngBookId. */ public long getLngBookId() { return lngBookId; } /** * @param lngBookId The lngBookId to set. */ public void setLngBookId(long lngBookId) { this.lngBookId = lngBookId; } /** * @return Returns the strBookName. */ public String getStrBookName() { return strBookName; } /**

Page 6: Hibernate

* @param strBookName The strBookName to set. */ public void setStrBookName(String strBookName) { this.strBookName = strBookName; }}Adding Mapping entries to contact.hbm.xmlAdd the following mapping code into the contact.hbm.xml file

<class name="roseindia.tutorial.hibernate.Book" table="book">     <id name="lngBookId" type="long" column="id" > <generator class="increment"/> </id>    <property name="strBookName"><column name="bookname" />    </property></class>

 Note that we have used increment for the generator class. *After adding the entries to the xml file copy it to the bin directory of your hibernate eclipse project(this step is required if you are using eclipse).Write the client program and test it outHere is the code of our client program to test the application.package roseindia.tutorial.hibernate;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class IdIncrementExample { public static void main(String[] args) { Session session = null; try{ // This step will read hibernate.cfg.xml and prepare hibernate for use SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); session =sessionFactory.openSession(); org.hibernate.Transaction tx = session.beginTransaction(); //Create new instance of Contact and set values in it by reading them from form object System.out.println("Inserting Book object into database.."); Book book = new Book(); book.setStrBookName("Hibernate Tutorial"); session.save(book); System.out.println("Book object persisted to the database."); tx.commit(); session.flush(); session.close(); }catch(Exception e){ System.out.println(e.getMessage()); }finally{ } }}To test the program Select Run->Run As -> Java Application from the eclipse menu bar. This will create a new record into the book table.Hibernate Update QueryHere 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;

Page 7: Hibernate

import java.util.Date;

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class UpdateExample {public static void main(String[] args) {Session sess = null;try {SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();Transaction tr = sess.beginTransaction();Insurance ins = (Insurance)sess.get(Insurance.class, new Long(1));ins.setInsuranceName("Jivan Dhara");ins.setInvestementAmount(20000);ins.setInvestementDate(new Date());sess.update(ins);tr.commit();sess.close();System.out.println("Update successfully!");}catch(Exception e){System.out.println(e.getMessage());}}} Output:

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select insurance0_.ID as ID0_0_, insurance0_.insurance_name as insurance2_0_0_, insurance0_.invested_amount as invested3_0_0_, insurance0_.investement_date as investem4_0_0_ from insurance insurance0_ where insurance0_.ID=?Hibernate: update insurance set insurance_name=?, invested_amount=?, investement_date=? where ID=?Update successfully!

"delete from Insurance insurance where id = 2"Here is the code of delete query: DeleteHQLExample.java package roseindia.tutorial.hibernate;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class DeleteHQLExample {public static void main(String[] args) {Session sess = null;try {SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String hql = "delete from Insurance insurance where id = 2";Query query = sess.createQuery(hql);int row = query.executeUpdate();

Page 8: Hibernate

if (row == 0){System.out.println("Doesn't deleted any row!");}else{System.out.println("DeletedRow: " + row);}sess.close();}catch(Exception e){System.out.println(e.getMessage());}}} Output:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: delete from insurance where ID=2Deleted Row: 1Hibernate Query LanguageHibernate 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 SyntaxAny Hibernate Query Language may consist of following elements:Clauses ,Aggregate functions ,Subqueries Clauses in the HQL are:from , select , where , order by , group by Aggregate functions are:avg(...), sum(...), min(...), max(...) , count(*) , count(...), count(distinct ...), count(all...) SubqueriesSubqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying database supports it.

Page 9: Hibernate

Preparing table for HQL ExamplesIn this lesson we will create insurance table and populate it with the data. We will use insurance table for rest of the HQL tutorial. To create the insurance table and insert the sample data, run the following sql query:/*Table structure for table `insurance` */drop table if exists `insurance`; CREATE TABLE `insurance` ( `ID` int(11) NOT NULL default '0',`insurance_name` varchar(50) default NULL, `invested_amount` int(11) default NULL, `investement_date` datetime default NULL, PRIMARY KEY (`ID`) ) TYPE=MyISAM;/*Data for the table `insurance` */insert into `insurance` values (1,'Car Insurance',1000,'2005-01-05 00:00:00');insert into `insurance` values (2,'Life Insurance',100,'2005-10-01 00:00:00');insert into `insurance` values (3,'Life Insurance',500,'2005-10-15 00:00:00');insert into `insurance` values (4,'Car Insurance',2500,'2005-01-01 00:00:00');insert into `insurance` values (5,'Dental Insurance',500,'2004-01-01 00:00:00');insert into `insurance` values (6,'Life Insurance',900,'2003-01-01 00:00:00');insert into `insurance` values (7,'Travel Insurance',2000,'2005-02-02 00:00:00');insert into `insurance` values (8,'Travel Insurance',600,'2005-03-03 00:00:00');insert into `insurance` values (9,'Medical Insurance',700,'2005-04-04 00:00:00');insert into `insurance` values (10,'Medical Insurance',900,'2005-03-03 00:00:00');insert into `insurance` values (11,'Home Insurance',800,'2005-02-02 00:00:00');insert into `insurance` values (12,'Home Insurance',750,'2004-09-09 00:00:00');insert into `insurance` values (13,'Motorcycle Insurance',900, '2004-06-06 00:00:00');insert into `insurance` values (14,'Motorcycle Insurance',780 ,'2005-03-03 00:00:00');Above Sql query will create insurance table and add the following data:ID insurance_name invested_amount investement_date1 Car Insurance 1000 2005-01-05 00:00:002 Life Insurance 100 2005-10-01 00:00:003 Life Insurance 500 2005-10-15 00:00:004 Car Insurance 2500 2005-01-01 00:00:005 Dental Insurance 500 2004-01-01 00:00:006 Life Insurance 900 2003-01-01 00:00:007 Travel Insurance 2000 2005-02-02 00:00:008 Travel Insurance 600 2005-03-03 00:00:009 Medical Insurance 700 2005-04-04 00:00:0010 Medical Insurance 900 2005-03-03 00:00:0011 Home Insurance 800 2005-02-02 00:00:0012 Home Insurance 750 2004-09-09 00:00:0013 Motorcycle Insurance 900 2004-06-06 00:00:0014 Motorcycle Insurance 780 2005-03-03 00:00:00Writing ORM for Insurance table: In this lesson we will write the java class and add necessary code in the contact.hbm.xml file. Create POJO class:Here is the code of our java file (Insurance.java), which we will map to the insurance table.package roseindia.tutorial.hibernate;import java.util.Date;public class Insurance {private long lngInsuranceId;private String insuranceName;private int investementAmount;private Date investementDate;

Page 10: Hibernate

public String getInsuranceName() {return insuranceName;}public void setInsuranceName(String insuranceName) {this.insuranceName = insuranceName;}public int getInvestementAmount() {return investementAmount;}public void setInvestementAmount(int investementAmount){this.investementAmount = investementAmount;}public Date getInvestementDate() {return investementDate;}public void setInvestementDate(Date investementDate) {this.investementDate = investementDate;}public long getLngInsuranceId() {return lngInsuranceId;}public void setLngInsuranceId(long lngInsuranceId) {this.lngInsuranceId = lngInsuranceId;}} Adding mappings into contact.hbm.xml fileAdd the following code into contact.hbm.xml file. <class name="roseindia.tutorial.hibernate.Insurance" table="insurance"><id name="lngInsuranceId" type="long" column="ID" > <generator class="increment"/> </id><property name="insuranceName"> <column name="insurance_name" /> </property><property name="investementAmount"> <column name="invested_amount" /> </property><property name="investementDate"> <column name="investement_date" /> </property></class> Now we have created the POJO class and necessary mapping into contact.hbm.xml fileHQL from clause ExampleIn this example you will learn how to use the HQL from clause. The from clause is the simplest possible Hibernate Query. Example of from clause is:from Insurance insurance. Here is the full code of the from clause example:package roseindia.tutorial.hibernate;import org.hibernate.Session;import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class SelectHQLExample {public static void main(String[] args) {Session session = null;try{// This step will read hibernate.cfg.xmland prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();//Using from ClauseString SQL_QUERY ="from Insurance insurance";Query query = session.createQuery(SQL_QUERY);

Page 11: Hibernate

for(Iterator it=query.iterate();it.hasNext();){Insurance insurance=(Insurance)it.next();System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("First Name: " + insurance.getInsuranceName());}session.close();}catch(Exception e){System.out.println(e.getMessage());}finally{}} } To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select insurance0_.ID as col_0_0_ from insurance insurance0_ID: 1Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Car InsuranceID: 2Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Life InsuranceID: 3Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Life InsuranceID: 4Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Car InsuranceID: 5Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Dental InsuranceID: 6Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Life InsuranceID: 7Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Travel InsuranceID: 8Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?

Page 12: Hibernate

First Name: Travel InsuranceID: 9Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Medical InsuranceID: 10Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Medical InsuranceID: 11Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Home InsuranceID: 12Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Home InsuranceID: 13Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Motorcycle InsuranceID: 14Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?First Name: Motorcycle InsuranceIn 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 insurancewhich 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.*;public class SelectClauseExample {public static void main(String[] args) {Session session = null;try{// This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();//Create Select Clause HQLString SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," +

Page 13: Hibernate

"insurance.investementAmount,insurance.investementDate from Insurance insurance";Query query = session.createQuery(SQL_QUERY);for(Iterator it=query.iterate();it.hasNext();){Object[] row = (Object[]) it.next();System.out.println("ID: " + row[0]);System.out.println("Name: " + row[1]);System.out.println("Amount: " + row[2]);}session.close();}catch(Exception e){System.out.println(e.getMessage());}finally{}}} To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:Hibernate: select insurance0_.ID as col_0_0_, insurance0_.insurance_name as col_1_0_, insurance0_.invested_amount as col_2_0_, insurance0_.investement_date as col_3_0_ from insurance insurance0_ ID: 1Name: Car InsuranceAmount: 1000ID: 2Name: Life InsuranceAmount: 100ID: 3Name: Life InsuranceAmount: 500ID: 4Name: Car InsuranceAmount: 2500ID: 5Name: Dental InsuranceAmount: 500ID: 6Name: Life InsuranceAmount: 900ID: 7Name: Travel InsuranceAmount: 2000ID: 8Name: Travel InsuranceAmount: 600ID: 9Name: Medical InsuranceAmount: 700ID: 10Name: Medical InsuranceAmount: 900ID: 11Name: Home InsuranceAmount: 800ID: 12Name: Home InsuranceAmount: 750ID: 13

Page 14: Hibernate

Name: Motorcycle InsuranceAmount: 900ID: 14Name: Motorcycle InsuranceAmount: 780In 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 org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;public class HibernateHQLCountFunctions {public static void main(String[] args) {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());}}} Output:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select count(*) as col_0_0_ from insurance insurance0_ group by insurance0_.IDTotal rows: 6In this section, we will show you, how to use the avg() function. Hibernate supports multiple aggregate functions. When they are used in HQL queries, they return an aggregate value

Page 15: Hibernate

( such as avg(...), sum(...), min(...), max(...) , count(*), count(...), count(distinct ...), count(all...) ) calculated from property values of all objects satisfying other query criteria. Following is a aggregate function (avg() function) with their respective syntax. avg( [ distinct | all ] object.property):The avg() function aggregates the average value of the given column. Table Name: insuranceID insurance_name invested_amount investement_date2 Life Insurance 25000 0000-00-00 00:00:001 Givan Dhara 20000 2007-07-30 17:29:053 Life Insurance 500 2005-10-15 00:00:004 Car Insurance 2500 2005-01-01 00:00:00

5Dental Insurance

500 2004-01-01 00:00:00

6 Life Insurance 900 2003-01-01 00:00:00

7 Travel Insurance

2000 2005-02-02 00:00:00

Here is the java code to retrieve the average value of "invested_amount" column from insurance table:package roseindia.tutorial.hibernate;import java.util.Iterator;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateHQLAvgFunction {public static void main(String[] args) {Session sess = null;try {SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String SQL_QUERY = "select avg (investementAmount) from Insurance insurance";Query query = sess.createQuery(SQL_QUERY);List list = query.list();System.out.println("Average of Invested Amount: " + list.get(0));}catch(Exception e){ System.out.println(e.getMessage());}}} Output:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select avg(insurance0_.invested_amount) as col_0_0_ from insurance insurance0_Average of Invested Amount: 7342.8571In this section, we will show you, how to use the Min() function. Hibernate supports multiple aggregate functions. When they are used in HQL queries, they return an aggregate value ( such as avg(...), sum(...), min(...), max(...) , count(*), count(...), count(distinct ...), count(all...) ) calculated from property values of all objects satisfying other query criteria. Following is a aggregate function (min() function) with their respective syntax. min( [ distinct | all ] object.property)The Min() function aggregates the minimum value of the given column. Table Name: insuranceID insurance_name invested_amount investement_date2 Life Insurance 25000 0000-00-00 00:00:001 Givan Dhara 20000 2007-07-30 17:29:05

Page 16: Hibernate

3 Life Insurance 500 2005-10-15 00:00:004 Car Insurance 2500 2005-01-01 00:00:00

5Dental Insurance

500 2004-01-01 00:00:00

6 Life Insurance 900 2003-01-01 00:00:00

7 Travel Insurance

2000 2005-02-02 00:00:00

Here is the java code to retrieve the minimum value of "invested_amount" column from insurance table:package roseindia.tutorial.hibernate;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateHQLMinFunction {public static void main(String[] args) {Session sess = null;try {SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String SQL_QUERY = "select min(investementAmount) from Insurance insurance";Query query = sess.createQuery(SQL_QUERY);List list = query.list();System.out.println("Min Invested Amount: " + list.get(0));}catch(Exception e){ System.out.println(e.getMessage());}}}Output:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select min(insurance0_.invested_amount) as col_0_0_ from insurance insurance0_Min Invested Amount: 500Where 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.*;public class WhereClauseExample {public static void main(String[] args) {Session session = null;try{SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();System.out.println("*******************************");System.out.println("Query using Hibernate Query Language");//Query using Hibernate Query LanguageString SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1'";Query query = session.createQuery(SQL_QUERY);

Page 17: Hibernate

for(Iterator it=query.iterate();it.hasNext();){Insurance insurance=(Insurance)it.next();System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("Name: "+ insurance. getInsuranceName());}System.out.println("******************************");System.out.println("Where Clause With Select Clause");//Where Clause With Select ClauseSQL_QUERY ="Select insurance.lngInsuranceId, insurance.insuranceName," +”insurance.investementAmount,insurance.investementDate from Insurance insurance "+ " where insurance.lngInsuranceId='1'";query = session.createQuery(SQL_QUERY);for(Iterator it=query.iterate();it.hasNext();){Object[] row = (Object[]) it.next();System.out.println("ID: " + row[0]);System.out.println("Name: " + row[1]);}System.out.println("******************************");session.close();}catch(Exception e){System.out.println(e.getMessage());}finally{} }} To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:Query using Hibernate Query LanguageHibernate: select insurance0_.ID as col_0_0_ from insurance insurance0_ where (insurance0_.ID='1')ID: 1Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Car Insurance*******************************Where Clause With Select ClauseHibernate: select insurance0_.ID as col_0_0_, insurance0_.insurance_name as col_1_0_, insurance0_.invested_amount as col_2_0_, insurance0_.investement_date as col_3_0_ from insurance insurance0_ where (insurance0_.ID='1')ID: 1Name: Car Insurance*******************************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.*;public class HQLGroupByExample {public static void main(String[] args) {Session session = null;try {SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session = sessionFactory.openSession();

Page 18: Hibernate

//Group By Clause ExampleString 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 {}}} To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:Hibernate: select sum(insurance0_.invested_amount) as col_0_0_, insurance0_.insurance_name as col_1_0_ from insurance insurance0_ group by insurance0_.insurance_name Invested Amount: 3500Insurance Name: Car InsuranceInvested Amount: 500Insurance Name: Dental InsuranceInvested Amount: 1550Insurance Name: Home InsuranceInvested Amount: 1500Insurance Name: Life InsuranceInvested Amount: 1600Insurance Name: Medical InsuranceInvested Amount: 1680Insurance Name: Motorcycle InsuranceInvested Amount: 2600Insurance Name: Travel InsuranceOrder 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.*;public class HQLOrderByExample {public static void main(String[] args) {Session session = null;try {// This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory =new Configuration().configure().buildSessionFactory();session = sessionFactory.openSession();//Order By ExampleString SQL_QUERY = " from Insurance as insurance order by insurance.insuranceName";Query query = session.createQuery(SQL_QUERY);for (Iterator it = query.iterate(); it.hasNext();) {Insurance insurance = (Insurance) it.next();

Page 19: Hibernate

System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("Name: " + insurance.getInsuranceName());}session.close();} catch (Exception e) {System.out.println(e.getMessage());} finally {}}} To run the example select Run-> Run As -> Java Application from the menu bar. Following out is displayed in the Eclipse console:Hibernate: select insurance0_.ID as col_0_0_ from insurance insurance0_ order by insurance0_.insurance_name ID: 1Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Car InsuranceID: 4Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Car InsuranceID: 5Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Dental InsuranceID: 11Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Home InsuranceID: 12Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Home InsuranceID: 2Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Life InsuranceID: 3Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Life InsuranceID: 6Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Life InsuranceID: 9Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as

Page 20: Hibernate

investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Medical InsuranceID: 10Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Medical InsuranceID: 13Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Motorcycle InsuranceID: 14Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Motorcycle InsuranceID: 7Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Travel InsuranceID: 8Hibernate: select insurance0_.ID as ID0_, insurance0_.insurance_name as insurance2_2_0_, insurance0_.invested_amount as invested3_2_0_, insurance0_.investement_date as investem4_2_0_ from insurance insurance0_ where insurance0_.ID=?Name: Travel InsuranceThe Criteria interface allows to create and execute object-oriented queries. It is powerful alternative to the HQL but has own limitations. Criteria Query is used mostly in case of multi criteria search screens, where HQL is not very effective. The interface org.hibernate.Criteria is used to create the criterion for the search. The org.hibernate.Criteria interface represents a query against a persistent class. The Session is a factory for Criteria instances. Here is a simple example of Hibernate Criterial Query:package roseindia.tutorial.hibernate;import org.hibernate.Session;import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class HibernateCriteriaQueryExample {public static void main(String[] args) {Session session = null;try {// This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session = sessionFactory.openSession();//Criteria Query ExampleCriteria crit = session.createCriteria(Insurance.class);List insurances = crit.list();for(Iterator it = insurances.iterator();it.hasNext();){Insurance insurance = (Insurance) it.next();System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("Name: " + insurance.getInsuranceName());}

Page 21: Hibernate

session.close();} catch (Exception e) {System.out.println(e.getMessage());} finally {} }} The above Criteria Query example selects all the records from the table and displays on the console. In the above code the following code creates a new Criteria instance, for the class Insurance:Criteria crit = session.createCriteria(Insurance.class);The code: List insurances = crit.list();creates the sql query and execute against database to retrieve the data. In this tutorial,, you will learn to use "between" with the Integer class. "Between" when used with the Integer object, It takes three parameters e.g. between("property_name",min_int,max_int).Restriction class provides built-in criterion via static factory methods. One important method of the Restriction class is between : which is used to apply a "between" constraint to the named propertyHere is the code of the class using "between" with the Integer class :package roseindia.tutorial.hibernate;import org.hibernate.Session;import org.hibernate.*;import org.hibernate.criterion.*;import org.hibernate.cfg.*;import java.util.*;public class HibernateCriteriaQueryBetweenTwoInteger {public static void main(String[] args) {Session session = null;try {SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session = sessionFactory.openSession();Criteria crit = session.createCriteria(Insurance.class);crit.add(Expression.between("investementAmount", new Integer(1000),new Integer(2500))); crit.setMaxResults(5); //Restricts the max rows to 5List insurances = crit.list();for(Iterator it = insurances.iterator();it.hasNext();){Insurance insurance =(Insurance) it.next();System.out.println("ID: " + insurance.getLngInsuranceId());System.out.println("Name: " + insurance.getInsuranceName());System.out.println("Amount: " + insurance.getInvestementAmount());}session.close();} catch (Exception e) {System.out.println(e.getMessage());} finally {} }} Output:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select this_.ID as ID0_0_, this_.insurance_name as insurance2_0_0_, this_.invested_amount as invested3_0_0_, this_.investement_date as investem4_0_0_ from insurance this_ where this_.invested_amount between ? and ? limit ?ID: 1Name: Car InsuranceAmount: 1000ID: 4Name: Car Insurance

Page 22: Hibernate

Amount: 2500ID: 7Name: Travel InsuranceAmount: 2000Native SQL is handwritten SQL for all database operations like create, update, delete and select. Hibernate Native Query also supports stored procedures. Hibernate allows you to run Native SQL Query for all the database operations, so you can use your existing handwritten sql with Hibernate, this also helps you in migrating your SQL/JDBC based application to Hibernate. In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to calculate average and then in another example select all the objects from table.Here is the code of Hibernate Native SQL:package roseindia.tutorial.hibernate;import org.hibernate.Session;import org.hibernate.*;import org.hibernate.criterion.*;import org.hibernate.cfg.*;import java.util.*;public class NativeQueryExample {public static void main(String[] args) {Session session = null;try{// This step will read hibernate.cfg.xml and prepare hibernate for useSessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();session =sessionFactory.openSession();/* Hibernate Native Query Average Examle*/String sql ="select stddev(ins.invested_amount) as stdErr, "+" avg(ins.invested_amount) as mean "+" from insurance ins";Query query = session.createSQLQuery(sql).addScalar("stdErr",Hibernate.DOUBLE). addScalar("mean",Hibernate.DOUBLE);Object [] amount = (Object [])query.uniqueResult(); System.out.println("mean amount: " + amount[0]);System.out.println("stdErr amount: " + amount[1]);/* Example to show Native query to select all the objects from database *//* Selecting all the objects from insurance table */List insurance = session.createSQLQuery("select {ins.*} from insurance ins").addEntity("ins", Insurance.class).list();for (Iterator it =insurance.iterator(); it.hasNext();) {Insurance insuranceObject= (Insurance) it.next();System.out.println("ID: " + insuranceObject.getLngInsuranceId());System.out.println("Name: + insuranceObject.getInsuranceName());}session.close();}catch(Exception e){System.out.println(e.getMessage()); e.printStackTrace();}}} Following query is used to calculate the average of invested amount:/*Hibernate Native Query Average Examle*/String sql ="select stddev(ins.invested_amount) as stdErr, "+ " avg(ins.invested_amount) as mean "+ " from insurance ins";The following code:Query query = session.createSQLQuery(sql).addScalar("stdErr",Hibernate.DOUBLE).addScalar("mean",Hibernate.DOUBLE);

Page 23: Hibernate

Creates a new instance of SQLQuery for the given SQL query string and the entities returned by the query are detached. To return all the entities from database we have used the following query:/* Example to show Native query to select all the objects from database *//* Selecting all the objects from insurance table */List insurance = session.createSQLQuery("select {ins.*} from insurance ins").addEntity("ins", Insurance.class).list();for (Iterator it = insurance.iterator(); it.hasNext();) {Insurance insuranceObject = (Insurance) it.next();System.out.println("ID: " + insuranceObject.getLngInsuranceId());System.out.println("Name: " + insuranceObject.getInsuranceName());}When you run the program through it should display the following result:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select stddev(ins.invested_amount) as stdErr, avg(ins.invested_amount) as mean from insurance insmean amount: 592.1584stdErr amount: 923.5714Hibernate: select ins.ID as ID0_, ins.insurance_name as insurance2_2_0_, ins.invested_amount as invested3_2_0_, ins.investement_date as investem4_2_0_ from insurance insID: 1Name: Car InsuranceID: 2Name: Life InsuranceID: 3Name: Life InsuranceID: 4Name: Car Insurance In this example you learned how to use Native Query with Hibernate.Association mappings: Association mappings comes in the list of the most difficult thing to get right. This section includes the canonical cases one by one. Here we starts the section from unidirectional mappings and comes to the bi-directional cases.We'll include the classification of associations that whether they map or not to an intervening join table and by multiplicity.Here we are not using the Nullable foreign keys since these keys do not require good practice in traditional data modeling. Hibernate does not require the foreign keys since mappings work even if we drop the nullability constraints.Hibernate HQL Inner JoinHibernate's HQL language is not capable for handling the "inner join on" clauses. If our domain entity model includes relationships defined between the related objects then the query like this Query query = session.createQuery("from Car car inner join Owner owner where owner.Name ='Vinod'");will work. HQL keeps the information of joining the Car and Owner classes according to the association mapping contained in the hbm.xml file. Since the association information is defined in the mapping file so there is no need to stipulate the join in the query. In the above query "from Car car where car.Owner.Name='Vinod'" will work too. Initialization of the collections and many-to-one mapping requires the explicit joins just to avoid lazy load errors.A unidirectional one-to-many association on a foreign key is rarely required.<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

Page 24: Hibernate

<hibernate-mapping><class name="net.roseindia.Dealer"><id name="id" type="int"><generator class="increment"/></id><property name="name" type="string"/><bag name="product" inverse="true" cascade="all,delete-orphan"><key column="did"/><one-to-many class="net.roseindia.Product"/></bag></class></hibernate-mapping> A unidirectional one-to-many association on a foreign key is rarely required.<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="net.roseindia.Product"><id name="id" type="int"><generator class="increment"/></id><property name="name" type="string"/><property name="did" type="int"/><property name="price" type="double"/><many-to-one name="dealer" class="net.roseindia.Dealer" column="did" insert="false" update="false"/></class></hibernate-mapping> Here is the hibernate code:In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.package net.roseindia;import java.util.Iterator;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Join {public static void main(String[] args) {Session sess = null;try{SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String sql_query = "from Product p inner join p.dealer as d";Query query = sess.createQuery(sql_query);Iterator ite = query.list().iterator();System.out.println("Dealer Name\t"+"Product Name\t"+"Price");while ( ite.hasNext() ) {Object[] pair = (Object[]) ite.next();Product pro = (Product) pair[0];Dealer dea = (Dealer) pair[1];System.out.print(pro.getName());System.out.print("\t"+dea.getName());System.out.print("\t\t"+pro.getPrice());System.out.println();}

Page 25: Hibernate

sess.close();}catch(Exception e ){System.out.println(e.getMessage());}}} Output:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select product0_.id as id1_0_, dealer1_.id as id0_1_, product0_.name as name1_0_, product0_.did as did1_0_, product0_.price as price1_0_, dealer1_.name as name0_1_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.idDealer Name Product Name PriceComputer Agrawal 23000.0Keyboard Agrawal 1500.0Computer Agrawal 100.0Mobile Mohan 15000.0PenDrive Mohan 200.0Laptop Ritu 200.0HardDisk Ritu 2500.0This example tries to make understand about the aggregate function of Hibernate with the help of example. In Hibernate HQL queries are capable of returning the results of the aggregate functions on properties. Collections can also be used with the aggregate functions with the select clause. Aggregate functions supports the following functions:min(...), max(...), sum(...), avg(...). ,count(*) ,count(distinct...), count(all..), count(...) The distinct and all keywords used above are identical as in SQL. A unidirectional one-to-many association on a foreign key is rarely required.<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="net.roseindia.Dealer"><id name="id" type="int"><generator class="increment"/></id><property name="name" type="string"/><bag name="product" inverse="true" cascade="all,delete-orphan"><key column="did"/><one-to-many class="net.roseindia.Product"/></bag></class></hibernate-mapping> A unidirectional one-to-many association on a foreign key is rarely required.<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="net.roseindia.Product"><id name="id" type="int"><generator class="increment"/></id><property name="name" type="string"/><property name="did" type="int"/><property name="price" type="double"/><many-to-one name="dealer" class="net.roseindia.Dealer" column="did" insert="false" update="false"/> </class></hibernate-mapping> In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to

Page 26: Hibernate

instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.Here is the hibernate code:package net.roseindia;import java.util.Iterator;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class AggregateFunctionExample {public static void main(String[] args) {Session sess = null;try{SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String sql_query = "select d.name,p.name,sum(p.price) as totalprice from Product p join p.dealer d group by p.name";Query query = sess.createQuery(sql_query);System.out.println("Dealer Name\t"+"Product Name\t"+"Price");for(Iterator it=query.iterate();it.hasNext();){Object[] row = (Object[]) it.next();System.out.print(row[0]);System.out.print("\t\t"+row[1]);System.out.print("\t"+row[2]);System.out.println();}sess.close();}catch(Exception e ){System.out.println(e.getMessage());}}} Output:Log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, sum(product0_.price) as col_2_0_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id group by product0_.nameDealer Name Product Name PriceAgrawal Computer 23100.0Ritu HardDisk 2500.0Agrawal Keyboard 1500.0Ritu Laptop 200.0Mohan Mobile 15000.0Mohan PenDrive 200.0In this section, you will learn about the subqueries with an appropriate example.Subqueries in hibernate can be referred as the queries that are surrounded by parentheses (). Subqueries solves the purpose of grouping, ordering , narrowing and aggregating the resultant of the query by using the where clause. Notice that the subqueries get executed prior to the main query. The HQL queries may contain the subqueries only in case of if the subqueries are supported by the underline database.A unidirectional one-to-many association on a foreign key is rarely required.<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping

Page 27: Hibernate

PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="net.roseindia.Dealer"><id name="id" type="int"><generator class="increment"/></id><property name="name" type="string"/><bag name="product" inverse="true" cascade="all,delete-orphan"><key column="did"/><one-to-many class="net.roseindia.Product"/></bag></class></hibernate-mapping> A unidirectional one-to-many association on a foreign key is rarely required.<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="net.roseindia.Product"><id name="id" type="int"><generator class="increment"/></id><property name="name" type="string"/><property name="did" type="int"/><property name="price" type="double"/><many-to-one name="dealer" class="net.roseindia.Dealer" column="did" insert="false" update="false"/></class></hibernate-mapping> Here is the hibernate code:In this example first we create the session object with the help of the SessionFactory interface. Then we use the createQuery() method of the Session object which returns a Query object. Now we use the openSession() method of the SessionFactory interface simply to instantiate the Session object. And the we retrieve the data from the database store it in that Query object and iterate this object with the help of Iterator and finally displays the requested data on the console.package net.roseindia;import java.util.Iterator;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class Subqueries {public static void main(String[] args) {Session sess = null;try{SessionFactory fact = new Configuration().configure().buildSessionFactory();sess = fact.openSession();String sql_query = "select d.name,p.name,p.price from Product p join p.dealer d where p.price in(select p.price from p where p.price > 1500)";Query query = sess.createQuery(sql_query);System.out.println("Dealer Name\t"+"Product Name\t"+"Price");for(Iterator it=query.iterate();it.hasNext();){Object[] row = (Object[]) it.next();System.out.print(row[0]);System.out.print("\t\t"+row[1]); System.out.print("\t"+row[2]);System.out.println(); }sess.close();}catch(Exception e ){System.out.println(e.getMessage());}}} Output:log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.Hibernate: select dealer1_.name as col_0_0_, product0_.name as col_1_0_, product0_.price as col_2_0_ from Product product0_ inner join Dealer dealer1_ on product0_.did=dealer1_.id where product0_.price in (select product0_.price from Product product0_ where product0_.price>1500)Dealer Name Product Name PriceAgrawal Computer 23000.0

Page 28: Hibernate

Mohan Mobile 15000.0Ritu HardDisk 2500.0