You are on page 1of 117

Introduction to Hibernate 3.0 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 reduce the development time. Hibernate is not the best solutions for data centric applications that only uses the storedprocedures 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 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.

Detailed features are available at http://www.hibernate.org/About/RoadMap. Hibernate Architecture In this lesson you will learn the architecture of Hibernate. The following diagram describes the high level architecture of hibernate:

The above diagram shows that Hibernate is using the database and configuration data to provide persistence services (and persistent objects) to the application. To use Hibernate, it is required to create Java classes that represents the table in the database and then map the instance variable in the class with the columns in the database. Then Hibernate can be used to perform operations on the database like select, insert, update and delete the records in the table. Hibernate automatically creates the query to perform these operations. Hibernate architecture has three main components:

Connection Management: Hibernate 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 provides 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. 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. <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url"> jdbc:mysql://localhost/hibernatetutorial</property> <property name="hibernate.connection.username">root</property> <property 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> Here is the code: 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: DB2 - org.hibernate.dialect.DB2Dialect HypersonicSQL - org.hibernate.dialect.HSQLDialect Informix - org.hibernate.dialect.InformixDialect Ingres - org.hibernate.dialect.IngresDialect Interbase - org.hibernate.dialect.InterbaseDialect Pointbase - org.hibernate.dialect.PointbaseDialect PostgreSQL - org.hibernate.dialect.PostgreSQLDialect Mckoi SQL - org.hibernate.dialect.MckoiDialect Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect MySQL - org.hibernate.dialect.MySQLDialect Oracle (any version) - org.hibernate.dialect.OracleDialect Oracle 9 - org.hibernate.dialect.Oracle9Dialect Progress - org.hibernate.dialect.ProgressDialect FrontBase - org.hibernate.dialect.FrontbaseDialect SAP DB - org.hibernate.dialect.SAPDBDialect Sybase - org.hibernate.dialect.SybaseDialect Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect The <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 Contact 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 string) { firstName = string; } /** * @param string sets the Last Name */ public void setLastName(String string) { lastName = string; } /** * @return ID Returns ID */ public long getId() { return id; } /** * @param l Sets the ID */

public void setId(long l) { id = l; } } Mapping the Contact Object to the Database Contact 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/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT"> <id name="id" type="long" column="ID" > <generator class="assigned"/> </id> <property name="firstName"> <column name="FIRSTNAME" /> </property> <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 into Contact table */ public class FirstExample { 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(); //Create new instance of Contact and set values in it by reading them from form object System.out.println("Inserting Record"); Contact contact = new Contact(); contact.setId(3); contact.setFirstName("Deepak"); contact.setLastName("Kumar"); contact.setEmail("deepak_38@yahoo.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.

Running First Hibernate 3.0 Example Hibernate is free open source software it can be download from http://www.hibernate.org/6.html. Visit the site and download Hibernate 3.0. You can download the Hibernate and install it yourself. But I have provided very thing in one zip file. Download the example code and library from here and extract the content in your favorite directory say "C:\hibernateexample". Download file contains the Eclipse project. To run the example you should have the Eclipse IDE on your machine. Start the Eclipse project and select Java Project as shown below.

Click on "Next" button. In the next screen leave the output folder as default "hibernateexample/bin".

Click on the "Finish" button.

Now Open the FirstExample.java in the editor as show below.

Copy contact.hbm.xml, and hibernate.cfg.xml in the bin directory of the project using windows explorer. To run the example select Run-> Run As -> Java Application from the menu bar as shown below.

This will run the Hibernate example program in Eclipse following output will displayed on the Eclipse Console.

In this section I showed you how to run the first Hibernate 3.0 example. Understanding Hibernate O/R Mapping In the last example we created contact.hbm.xml to map Contact Object to the Contact table in the database. Now let's understand the each component of the mapping file. To recall here is the content of contact.hbm.xml: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">

<id name="id" type="long" column="ID" > <generator class="assigned"/> </id> <property name="firstName"> <column name="FIRSTNAME" /> </property> <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: 1. <hibernate-mapping> element The first or root element of hibernate mapping document is <hibernate-mapping> element. Between the <hibernate-mapping> tag class element(s) are present. 2. <class> element The <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. 3. <id> element The <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. 4. <generator> element The <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. 5. <property> element The 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. Understanding Hibernate <generator> element In this lesson you will learn about hibernate <generator> method in detail. Hibernate generator element generates the primary key for new record. There are many options provided by the generator method to be used in different situations. The <generator> element This 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 It generates identifiers of type long, short or int that are unique only when no other increment process is inserting data into the same table. It should not the used in the clustered environment. It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and identity HypersonicSQL. The returned identifier is of type long, short or int. The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, sequence McKoi or a generator in Interbase. The returned identifier is of type long, short or int 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 hilo 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. The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of seqhilo type long, short or int, given a named database sequence. uuid The 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

guid native assigned select foreign

string of hexadecimal digits of length 32. It uses a database-generated GUID string on MS SQL Server and MySQL. It picks identity, sequence or hilo depending upon the capabilities of the underlying database. Lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified. retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value. uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association.

Using Hibernate <generator> to generate id incrementally As we have seen in the last section that the increment class generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. In this lesson I will show you how to write running program to demonstrate it. You should not use this method to generate the primary key in case of clustured environment. In this we will create a new table in database, add mappings in the contact.hbm.xml file, develop the POJO class (Book.java), write the program to test it out. 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". /** * @author Deepak Kumar * * http://www.roseindia.net * Java Class to map to the database Book table */ 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; } /** * @param strBookName The strBookName to set. */ public void setStrBookName(String strBookName) { this.strBookName = strBookName; } } Adding Mapping entries to contact.hbm.xml Add 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 out Here is the code of our client program to test the application. /** * @author Deepak Kumar *

* http://www.roseindia.net * Example to show the increment class of hibernate generator element to * automatically generate the primay key */ package roseindia.tutorial.hibernate; //Hibernate Imports 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 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 org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class UpdateExample { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration() .configure().buildSessionFactory(); sess = fact.openSession(); Transaction tr = sess.beginTransaction(); Insurance ins = (Insurance)sess.get (Insurance.class, new Long(1)); ins.setInsuranceName("Jivan Dhara");

ins.setInvestementAmount(20000); ins.setInvestementDate(new Date()); sess.update(ins); tr.commit(); sess.close(); System.out.println("Update 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! 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 org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class DeleteHQLExample { /** * @author vinod Kumar

* * http://www.roseindia.net Hibernate Criteria Query Example * */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); String hql = "delete from Insurance insurance where id = 2"; Query query = sess.createQuery(hql); int row = query.executeUpdate(); if (row == 0){ System.out.println("Doesn' t deleted any row!"); } else{ System.out.println("Deleted Row: " + row); } sess.close(); } catch(Exception e){ System.out.println(e.getMessage()); } } } 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=2 Deleted Row: 1 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.

Preparing table for HQL Examples In 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_date 1 Car Insurance 1000 2005-01-05 00:00:00 2 Life Insurance 100 2005-10-01 00:00:00 3 Life Insurance 500 2005-10-15 00:00:00 4 Car Insurance 2500 2005-01-01 00:00:00 5 Dental Insurance 500 2004-01-01 00:00:00 6 Life Insurance 900 2003-01-01 00:00:00

7 8 9 10 11 12 13

Travel Insurance 2000 2005-02-02 00:00:00 Travel Insurance 600 2005-03-03 00:00:00 Medical Insurance 700 2005-04-04 00:00:00 Medical Insurance 900 2005-03-03 00:00:00 Home Insurance 800 2005-02-02 00:00:00 Home Insurance 750 2004-09-09 00:00:00 Motorcycle 900 2004-06-06 00:00:00 Insurance 14 Motorcycle 780 2005-03-03 00:00:00 Insurance In the future lessons we will use this table to write different HQL examples. Writing 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; /** * @author Deepak Kumar * * http://www.roseindia.net * Java Class to map to the database insurance table */ public class Insurance { private long lngInsuranceId; private String insuranceName; private int investementAmount; private Date investementDate; /** * @return Returns the insuranceName. */ public String getInsuranceName() { return insuranceName; } /** * @param insuranceName The insuranceName to set. */ public void setInsuranceName(String insuranceName) { this.insuranceName = insuranceName;

} /** * @return Returns the investementAmount. */ public int getInvestementAmount() { return investementAmount; } /** * @param investementAmount The investementAmount to set. */ public void setInvestementAmount(int investementAmount) { this.investementAmount = investementAmount; } /** * @return Returns the investementDate. */ public Date getInvestementDate() { return investementDate; } /** * @param investementDate The investementDate to set. */ public void setInvestementDate(Date investementDate) { this.investementDate = investementDate; } /** * @return Returns the lngInsuranceId. */ public long getLngInsuranceId() { return lngInsuranceId; } /** * @param lngInsuranceId The lngInsuranceId to set. */ public void setLngInsuranceId(long lngInsuranceId) { this.lngInsuranceId = lngInsuranceId; } } Adding mappings into contact.hbm.xml file Add 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 file. HQL from clause Example In 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.*; /** * @author Deepak Kumar * * http://www.roseindia.net * Select HQL Example */ public class SelectHQLExample { 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();

//Using from Clause String SQL_QUERY ="from Insurance insurance"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Insurance insurance=(Insurance)it.next(); System.out.println("ID: " + insurance.getLngInsuranceId()); System.out.println("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: 1 Hibernate: 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 Insurance ID: 2 Hibernate: 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 Insurance ID: 3 Hibernate: 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 Insurance ID: 4

Hibernate: 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 Insurance ID: 5 Hibernate: 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 Insurance ID: 6 Hibernate: 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 Insurance ID: 7 Hibernate: 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 Insurance ID: 8 Hibernate: 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 Insurance ID: 9 Hibernate: 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 Insurance ID: 10 Hibernate: 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 Insurance ID: 11 Hibernate: 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 Insurance ID: 12 Hibernate: 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 Insurance ID: 13

Hibernate: 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 Insurance ID: 14 Hibernate: 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 Insurance 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[] 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(); //Create Select Clause HQL String SQL_QUERY ="Select insurance. lngInsuranceId,insurance.insuranceName," + "insurance.investementAmount,insurance. investementDate from Insurance insurance"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Object[] row = (Object[]) it.next(); System.out.println("ID: " + row[0]); System.out.println("Name: " + row[1]); System.out.println("Amount: " + row[2]); } 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: 1 Name: Car Insurance Amount: 1000 ID: 2 Name: Life Insurance Amount: 100 ID: 3 Name: Life Insurance Amount: 500 ID: 4 Name: Car Insurance Amount: 2500 ID: 5 Name: Dental Insurance Amount: 500 ID: 6 Name: Life Insurance

Amount: 900 ID: 7 Name: Travel Insurance Amount: 2000 ID: 8 Name: Travel Insurance Amount: 600 ID: 9 Name: Medical Insurance Amount: 700 ID: 10 Name: Medical Insurance Amount: 900 ID: 11 Name: Home Insurance Amount: 800 ID: 12 Name: Home Insurance Amount: 750 ID: 13 Name: Motorcycle Insurance Amount: 900 ID: 14 Name: Motorcycle Insurance Amount: 780 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 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) { // 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()); } } } 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_.ID Total rows: 6

Hibernate Avg() Function (Aggregate Functions) In 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 ( 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: insurance ID insurance_name invested_amount investement_date 2 Life Insurance 25000 0000-00-00 00:00:00 1 Givan Dhara 20000 2007-07-30 17:29:05 3 Life Insurance 500 2005-10-15 00:00:00 4 Car Insurance 2500 2005-01-01 00:00:00 5 Dental 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 { /** * @Vinod kumar */ public static void main(String[] args) { // TODO Auto-generated method stub 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.8571 Hibernate Max() Function (Aggregate Functions) In this section, we will show you, how to use the Max() 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 (max() function) with their respective syntax. max( [ distinct | all ] object.property) The Max() function aggregates the maximum value of the given column. Table Name: insurance ID insurance_name invested_amount investement_date 2 Life Insurance 25000 0000-00-00 00:00:00 1 Givan Dhara 20000 2007-07-30 17:29:05 3 Life Insurance 500 2005-10-15 00:00:00 4 Car Insurance 2500 2005-01-01 00:00:00 5 Dental 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 maximum 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.Transaction; import org.hibernate.cfg.Configuration; public class HibernateHQLMaxFunction { /** * mail_mevinod@yahoo.co.in */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); String SQL_QUERY = "select max(investementAmount)from Insurance insurance"; Query query = sess.createQuery(SQL_QUERY); List list = query.list(); System.out.println("Max Invested Amount: " + list.get(0)); 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 max(insurance0_.invested_amount) as col_0_0_ from insurance insurance0_ Max Invested Amount: 25000 Hibernate Min() Function (Aggregate Functions) In 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: insurance ID insurance_name invested_amount investement_date 2 Life Insurance 25000 0000-00-00 00:00:00 1 Givan Dhara 20000 2007-07-30 17:29:05 3 Life Insurance 500 2005-10-15 00:00:00 4 Car Insurance 2500 2005-01-01 00:00:00 5 Dental 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 { /** * @Vinod Kumar */ public static void main(String[] args) { // TODO Auto-generated method stub 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: 500 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 Example */ public class WhereClauseExample { public static void main(String[] args) { Session session = null; try{ // This step will read hibernate.cfg.xml and prepare hibernate for use SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession(); System.out.println("*******************************"); System.out.println("Query using Hibernate Query Language"); //Query using Hibernate Query Language String SQL_QUERY =" from Insurance as insurance where insurance.lngInsuranceId='1'"; Query query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Insurance insurance=(Insurance)it.next(); System.out.println("ID: " + insurance.getLngInsuranceId()); System.out.println("Name: " + insurance. getInsuranceName()); } System.out.println("*******************************"); System.out.println("Where Clause With Select Clause"); //Where Clause With Select Clause SQL_QUERY ="Select insurance.lngInsuranceId,insurance.insuranceName," + "insurance.investementAmount,insurance.investementDate from Insurance insurance "+ " where insurance.lngInsuranceId='1'"; query = session.createQuery(SQL_QUERY); for(Iterator it=query.iterate();it.hasNext();){ Object[] row = (Object[]) it.next(); System.out.println("ID: " + row[0]); System.out.println("Name: " + row[1]); } System.out.println("*******************************"); 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 Language Hibernate: select insurance0_.ID as col_0_0_ from insurance insurance0_ where (insurance0_.ID='1') ID: 1

Hibernate: 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 Clause 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_ where (insurance0_.ID='1') ID: 1 Name: Car Insurance ******************************* 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[] 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(); //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 { } } } 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 insurance0_.insurance_name as col_1_0_ from insurance insurance0_ insurance0_.insurance_name Invested Amount: 3500 Insurance Name: Car Insurance Invested Amount: 500 Insurance Name: Dental Insurance Invested Amount: 1550 Insurance Name: Home Insurance Invested Amount: 1500 Insurance Name: Life Insurance Invested Amount: 1600 Insurance Name: Medical Insurance Invested Amount: 1680 Insurance Name: Motorcycle Insurance Invested Amount: 2600 Insurance Name: Travel Insurance col_0_0_, group by

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[] 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(); //Order By Example String SQL_QUERY = " from Insurance as insurance order by insurance.insuranceName"; Query query = session.createQuery(SQL_QUERY); for (Iterator it = query.iterate(); it.hasNext();) { Insurance insurance = (Insurance) it.next(); System.out.println("ID: " + insurance.getLngInsuranceId()); System.out.println("Name: " + insurance.getInsuranceName()); } session.close(); } catch (Exception e) { System.out.println(e.getMessage()); } finally { } } } 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: 1 Hibernate: 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 ID: 4

Hibernate: 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 ID: 5 Hibernate: 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 Insurance ID: 11 Hibernate: 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 Insurance ID: 12 Hibernate: 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 Insurance ID: 2 Hibernate: 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 Insurance ID: 3 Hibernate: 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 Insurance ID: 6 Hibernate: 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 Insurance ID: 9 Hibernate: 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 Insurance ID: 10 Hibernate: 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 Insurance ID: 13

Hibernate: 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 Insurance ID: 14 Hibernate: 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 Insurance ID: 7 Hibernate: 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 Insurance ID: 8 Hibernate: 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 Insurance Hibernate Criteria Query Example The Criteria interface allows creating and executing 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.*; /** * @author Deepak Kumar * * http://www.roseindia.net Hibernate Criteria Query Example * */public class HibernateCriteriaQueryExample { 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(); //Criteria Query Example Criteria 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()); } 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. Criteria Query Examples In the last lesson we learnt how to use Criteria Query to select all the records from Insurance table. In this lesson we will learn how to restrict the results returned from the database. Different method provided by Criteria interface can be used with the help of Restrictions to restrict the records fetched from database. Criteria Interface provides the following methods: Method Description The Add method adds a Criterion to constrain the results to be add retrieved. addOrder Add an Order to the result set. createAlias Join an association, assigning an alias to the joined entity This method is used to create a new Criteria, "rooted" at the createCriteria associated entity.

This method is used to set a fetch size for the underlying JDBC query. setFirstResult This method is used to set the first result to be retrieved. This method is used to set a limit upon the number of objects to setMaxResults be retrieved. This method is used to instruct the Hibernate to fetch and return uniqueResult the unique records from database. setFetchSize Class Restriction provides built-in criterion via static factory methods. Important methods of the Restriction class are: Method Description This is used to apply an "equals" constraint to each Restriction.allEq property in the key set of a Map This is used to apply a "between" constraint to the Restriction.between named property This is used to apply an "equal" constraint to the Restriction.eq named property This is used to apply a "greater than or equal" Restriction.ge constraint to the named property This is used to apply a "greater than" constraint to Restriction.gt the named property This is used to apply an "equal" constraint to the Restriction.idEq identifier property This is case-insensitive "like", similar to Postgres Restriction.ilike ilike operator This is used to apply an "in" constraint to the named Restriction.in property This is used to apply an "is not null" constraint to Restriction.isNotNull the named property This is used to apply an "is null" constraint to the Restriction.isNull named property This is used to apply a "less than or equal" Restriction.le constraint to the named property This is used to apply a "like" constraint to the Restriction.like named property This is used to apply a "less than" constraint to the Restriction.lt named property This is used to apply a "less than" constraint to two Restriction.ltProperty properties This is used to apply a "not equal" constraint to the Restriction.ne named property

Restriction.neProperty Restriction.not Restriction.or

This is used to apply a "not equal" constraint to two properties This returns the negation of an expression This returns the disjuction of two expressions

Here is an example code that shows how to use Restrictions.like method and restrict the maximum rows returned by query by setting the Criteria.setMaxResults() value to 5. package roseindia.tutorial.hibernate; import org.hibernate.Session; import org.hibernate.*; import org.hibernate.criterion.*; import org.hibernate.cfg.*; import java.util.*; /** * @author Deepak Kumar * * http://www.roseindia.net Hibernate Criteria Query Example * */public class HibernateCriteriaQueryExample2 { 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(); //Criteria Query Example Criteria crit = session.createCriteria(Insurance.class); crit.add(Restrictions.like("insuranceName", "%a%")); //Like condition crit.setMaxResults(5); //Restricts the max rows to 5 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()); }

session.close(); } catch (Exception e) { System.out.println(e.getMessage()); } finally { } } } Hibernate's Built-in criterion: Between (using Integer) 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 property Here 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.*; /** * @author vinod Kumar * * http://www.roseindia.net Hibernate Criteria Query Example * */public class HibernateCriteriaQueryBetweenTwoInteger { 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(); //Criteria Query Example

Criteria crit = session.createCriteria(Insurance.class); crit.add(Expression.between(" investementAmount", new Integer(1000), new Integer(2500))); // Between condition crit.setMaxResults(5); // Restricts the max rows to 5 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()); 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: 1 Name: Car Insurance Amount: 1000 ID: 4 Name: Car Insurance Amount: 2500 ID: 7 Name: Travel Insurance Amount: 2000

Hibernate's Built-in criterion: Between (using with Date) In this section, you will learn to use "between" i.e. one of the built-in hibernate criterions. 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 property In this tutorial, "Between" is used with the date object. It takes three parameters e.g. between("property_name",startDate,endDate) Here is the code of the class using "between" with the Date class: package roseindia.tutorial.hibernate; import org.hibernate.*; import org.hibernate.criterion.*; import org.hibernate.cfg.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * @author Deepak Kumar * * http://www.roseindia.net Hibernate Criteria Query Example * */public class HibernateCriteriaQueryBetweenDate { 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(); //Criteria Query Example Criteria crit = session.createCriteria(Insurance.class); DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date startDate = (Date)format.parse("2005-01-01 00:00:00"); Date endDate =

(Date)format.parse("2005-03-03 00:00:00"); crit.add(Expression.between ("investementDate", new Date(startDate.getTime()), new Date(endDate.getTime()))); // Between date condition crit.setMaxResults(5); // Restricts the max rows to 5 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()); System.out.println(" Amount: " + insurance.getInvestementAmount()); System.out.println(" Date: " + insurance.getInvestementDate()); } 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_.investement_date between ? and ? limit ? ID: 1 Name: Car Insurance Amount: 1000 Date: 2005-01-05 00:00:00.0 ID: 4 Name: Car Insurance Amount: 2500

Date: 2005-01-01 00:00:00.0 ID: 7 Name: Travel Insurance Amount: 2000 Date: 2005-02-02 00:00:00.0 ID: 8 Name: Travel Insurance Amount: 600 Date: 2005-03-03 00:00:00.0 Hibernate Criteria Expression (eq) In this section, you will learn to use the "eq" method. This is one of the most important method that is used to apply an "equal" constraint to the named property. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports eq() method in Expression class. In this tutorial, "Eq" is used with the date object. It takes two parameters e.g. eq("property_name",Object val). Table Name: insurance ID insurance_name invested_amount investement_date 0000-00-00 2 Life Insurance 25000 00:00:00 2007-07-30 1 Givan Dhara 20000 17:29:05 2005-10-15 3 Life Insurance 500 00:00:00 2005-01-01 4 Car Insurance 2500 00:00:00 2004-01-01 5 Dental Insurance 500 00:00:00 2003-01-01 6 Life Insurance 900 00:00:00 2005-02-02 7 Travel Insurance 2000 00:00:00 Here is the code of the class using "eq" Expression : package roseindia.tutorial.hibernate; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import java.util.List;

import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Expression; public class HibernateCriteriaQueryExpressionEq { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try{ SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = (Date)format.parse("2005-01-01 00:00:00"); crit.add(Expression.eq(" investementDate",date)); List list = crit.list(); for(Iterator it = list.iterator();it.hasNext();){ Insurance ins = (Insurance)it.next(); System.out.println(" Id: " + ins.getLngInsuranceId()); System.out.println(" Insurance Name: " + ins.getInsuranceName()); System.out.println(" Insurance Amount: " + ins.getInvestementAmount()); System.out.println(" Investement Date: " + ins.getInvestementDate()); } sess.clear(); } 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 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_.investement_date=? Id: 4 Insurance Name: Car Insurance Insurance Amount: 2500 Investement Date: 2005-01-01 00:00:00.0 Hibernate Criteria Expression (lt) In this section, you will learn to use the "lt" method. This is one of the most important method that is used to apply a "less than" constraint to the named property. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports lt() method in Expression class. In this tutorial, "lt" is used with the Integer object (invested_amount). It takes two parameters e.g. lt("property_name",Object val). Table Name: insurance ID insurance_name invested_amount investement_date 0000-00-00 2 Life Insurance 25000 00:00:00 2007-07-30 1 Givan Dhara 20000 17:29:05 2005-10-15 3 Life Insurance 500 00:00:00 2005-01-01 4 Car Insurance 2500 00:00:00 2004-01-01 5 Dental Insurance 500 00:00:00 2003-01-01 6 Life Insurance 900 00:00:00 2005-02-02 7 Travel Insurance 2000 00:00:00

Here is the code of the class using "lt" Expression : package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Expression; public class HibernateCriteriaQueryExpressionLt { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); crit.add(Expression.lt ("investementAmount",new Integer(900))); List list = crit.list(); for (Iterator it = list.iterator();it.hasNext();){ Insurance ins = (Insurance)it.next(); System.out.println("Insurance Id: " + ins.getLngInsuranceId()); System.out.println("Insurance Name: " + ins.getInsuranceName()); System.out.println("Insurance Amount: " + ins.getInvestementAmount()); System.out.println("Investement Date: " + ins.getInvestementDate()); } 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 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<? Insurance Id: 3 Insurance Name: Life Insurance Insurance Amount: 500 Investement Date: 2005-10-15 00:00:00.0 Insurance Id: 5 Insurance Name: Dental Insurance Insurance Amount: 500 Investement Date: 2004-01-01 00:00:00.0 Hibernate Criteria Expression (le) In this section, you will learn to use the "le" method. This is one of the most important method that is used to apply a "less than or equal" constraint to the named property. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports le() method in Expression class. In this tutorial, "le" is used with the Integer object (invested_amount). It takes two parameters e.g. le("property_name",Object val). Table Name: insurance ID insurance_name invested_amount investement_date 0000-00-00 2 Life Insurance 25000 00:00:00 2007-07-30 1 Givan Dhara 20000 17:29:05 2005-10-15 3 Life Insurance 500 00:00:00 2005-01-01 4 Car Insurance 2500 00:00:00 5 Dental 500 2004-01-01

Insurance 6 Life Insurance 7 Travel Insurance 900 2000

00:00:00 2003-01-01 00:00:00 2005-02-02 00:00:00

Here is the code of the class using "le" Expression : package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Expression; public class HibernateCriteriaQueryExpressionLe { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); crit.add(Expression.le(" investementAmount",new Integer(900))); List list = crit.list(); for (Iterator it = list.iterator();it.hasNext();){ Insurance ins = (Insurance)it.next(); System.out.println("Insurance Id: " + ins.getLngInsuranceId()); System.out.println("Insurance Name: " + ins.getInsuranceName()); System.out.println("Insurance

Amount: " + ins.getInvestementAmount()); System.out.println("Investement Date: " + ins.getInvestementDate()); } 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 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<=? Insurance Id: 3 Insurance Name: Life Insurance Insurance Amount: 500 Investement Date: 2005-10-15 00:00:00.0 Insurance Id: 5 Insurance Name: Dental Insurance Insurance Amount: 500 Investement Date: 2004-01-01 00:00:00.0 Insurance Id: 6 Insurance Name: Life Insurance Insurance Amount: 900 Investement Date: 2003-01-01 00:00:00.0 Hibernate Criteria Expression (gt) In this section, you will learn to use the "gt" method. This is one of the most important method that is used to apply a "greater than" constraint to the named property Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports gt() method in Expression class. In this tutorial, "gt" is used with the Long object (ID). It takes two parameters e.g. ge("property_name",Object val). Table Name: insurance ID insurance_name invested_amount investement_date 2 Life Insurance 25000 0000-00-00

1 Givan Dhara 3 Life Insurance 4 Car Insurance

20000 500 2500

5 Dental Insurance 500 6 Life Insurance 900

7 Travel Insurance 2000

00:00:00 2007-07-30 17:29:05 2005-10-15 00:00:00 2005-01-01 00:00:00 2004-01-01 00:00:00 2003-01-01 00:00:00 2005-02-02 00:00:00

Here is the code of the class using "gt" Expression : package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Expression; public class HibernateCriteriaQueryExpressionGt { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); crit.add(Expression.gt ("lngInsuranceId",new Long(3)));

List list = crit.list(); for (Iterator it = list.iterator();it.hasNext();){ Insurance ins = (Insurance)it.next(); System.out.println(" Insurance Id: " + ins.getLngInsuranceId()); System.out.println(" Insurance Name: " + ins.getInsuranceName()); System.out.println(" Insurance Amount: " + ins.getInvestementAmount()); System.out.println(" Investement Date: " + ins.getInvestementDate()); } 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 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_.ID>? Insurance Id: 4 Insurance Name: Car Insurance Insurance Amount: 2500 Investement Date: 2005-01-01 00:00:00.0 Insurance Id: 5 Insurance Name: Dental Insurance Insurance Amount: 500 Investement Date: 2004-01-01 00:00:00.0 Insurance Id: 6 Insurance Name: Life Insurance Insurance Amount: 900 Investement Date: 2003-01-01 00:00:00.0 Insurance Id: 7 Insurance Name: Travel Insurance Insurance Amount: 2000 Investement Date: 2005-02-02 00:00:00.0

Hibernate Criteria Expression (ge) In this section, you will learn to use the "ge" method. This is one of the most important method that is used to apply a "greater than or equal" constraint to the named property. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. That supports ge() method in Expression class. In this tutorial, "ge" is used with the Long object (ID). It takes two parameters e.g. ge("property_name",Object val).

Table Name: insurance ID insurance_name invested_amount investement_date 0000-00-00 2 Life Insurance 25000 00:00:00 2007-07-30 1 Givan Dhara 20000 17:29:05 2005-10-15 3 Life Insurance 500 00:00:00 2005-01-01 4 Car Insurance 2500 00:00:00 Dental 2004-01-01 5 500 Insurance 00:00:00 2003-01-01 6 Life Insurance 900 00:00:00 Travel 2005-02-02 7 2000 Insurance 00:00:00 Here is the code of the class using "ge" Expression : package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Expression; public class HibernateCriteriaQueryExpressionGe {

/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try{ SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); crit.add(Expression.ge ("lngInsuranceId",new Long(3))); List list = crit.list(); for(Iterator it = list.iterator();it.hasNext();){ Insurance ins = (Insurance)it.next(); System.out.println( "Id: " + ins.getLngInsuranceId()); System.out.println( "Insurance Name: " + ins.getInsuranceName()); System.out.println( "Insurance Amount: " + ins.getInvestementAmount()); System.out.println( "Investement Date: " + ins.getInvestementDate()); } sess.clear(); } 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 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_.ID>=? Id: 3 Insurance Name: Life Insurance

Insurance Amount: 500 Investement Date: 2005-10-15 00:00:00.0 Id: 4 Insurance Name: Car Insurance Insurance Amount: 2500 Investement Date: 2005-01-01 00:00:00.0 Id: 5 Insurance Name: Dental Insurance Insurance Amount: 500 Investement Date: 2004-01-01 00:00:00.0 Id: 6 Insurance Name: Life Insurance Insurance Amount: 900 Investement Date: 2003-01-01 00:00:00.0 Id: 7 Insurance Name: Travel Insurance Insurance Amount: 2000 Investement Date: 2005-02-02 00:00:00.0 Hibernate Criteria Expression (and) In this section, you will learn to use the "and" method. This is one of the most important method that returns the conjunctions of two expressions. You can also build the nested expressions using 'and' and 'or'. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. Expression and(Criterion LHS, Criterion RHS): This method returns the conjunctions of two expressions. Both conditions are 'true' then it xecutes the query otherwise not. In this tutorial, "and" is used : Expression.and(Expression.gt("lngInsuranceId", new Long(3), Expression.lt("IngInsuranceId", new Long(6))). Table Name: insurance ID insurance_name invested_amount investement_date 0000-00-00 2 Life Insurance 25000 00:00:00 2007-07-30 1 Givan Dhara 20000 17:29:05 2005-10-15 3 Life Insurance 500 00:00:00 2005-01-01 4 Car Insurance 2500 00:00:00 5 Dental Insurance 500 2004-01-01

6 Life Insurance

900

7 Travel Insurance 2000

00:00:00 2003-01-01 00:00:00 2005-02-02 00:00:00

Here is the code of the class using "and" Expression : package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Expression; public class HibernateCriteriaQueryExpressionAnd { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); crit.add(Expression.and (Expression.gt("lngInsuranceId",new Long(3)), Expression.lt("lngInsuranceId",new Long(6)))); List list = crit.list(); for(Iterator it = list.iterator();it.hasNext();){ Insurance ins = (Insurance)it.next(); System.out.println( "Insurance Id: " + ins.getLngInsuranceId()); System.out.println(

"Insurance Name: " + ins.getInsuranceName()); System.out.println( "Invested Amount: " + ins.getInvestementAmount()); System.out.println( "Investement Date: " + ins.getInvestementDate()); } 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 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_.ID>? and this_.ID<?) Insurance Id: 4 Insurance Name: Car Insurance Invested Amount: 2500 Investement Date: 2005-01-01 00:00:00.0 Insurance Id: 5 Insurance Name: Dental Insurance Invested Amount: 500 Investement Date: 2004-01-01 00:00:00.0 Hibernate Criteria Expression (or) In this section, you will learn to use the "or" method. This is one of the most important method that returns the disjunction of the two expressions. You can also build the nested expressions using 'and' and 'or'. Expressions: The Hibernate Criteria API supports a rich set of comparison operators. Some standard SQL operators are =, <, ?, >, ?. Expression or(Criterion LHS, Criterion RHS): This method returns the disjuction of two expressions. Any given condition is 'true' then it executes the query. In this tutorial, "or" is used : Expression.or(Expression.eq("lngInsuranceId", new Long(3), Expression.eq("IngInsuranceId", new Long(6))). Table Name: insurance ID insurance_name invested_amount investement_date

2 Life Insurance 1 Givan Dhara 3 Life Insurance 4 Car Insurance

25000 20000 500 2500

5 Dental Insurance 500 6 Life Insurance 900

7 Travel Insurance 2000

0000-00-00 00:00:00 2007-07-30 17:29:05 2005-10-15 00:00:00 2005-01-01 00:00:00 2004-01-01 00:00:00 2003-01-01 00:00:00 2005-02-02 00:00:00

Here is the code of the class using "or" Expression : package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Expression; public class HibernateCriteriaQueryExpressionOr { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess. createCriteria(Insurance.class); crit.add(Expression.or

(Expression.eq("lngInsuranceId",new Long(3)), Expression.eq("lngInsuranceId",new Long(6)))); List list = crit.list(); for (Iterator it = list.iterator();it.hasNext();){ Insurance ins = (Insurance)it.next(); System.out.println("Insurance Id: " + ins.getLngInsuranceId()); System.out.println("Insurance Name: " + ins.getInsuranceName()); System.out.println("Invested Amount: " + ins.getInvestementAmount()); System.out.println("Investement Date:" + ins.getInvestementDate()); } 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 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_.ID=? or this_.ID=?) Insurance Id: 3 Insurance Name: Life Insurance Invested Amount: 500 Investement Date:2005-10-15 00:00:00.0 Insurance Id: 6 Insurance Name: Life Insurance Invested Amount: 900 Investement Date:2003-01-01 00:00:00.0 Insert Data into Database Using Hibernate Native SQL In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to insert data into database. Native SQL is handwritten SQL for all database operations like insert, update, delete and select. Hibernate provides a powerful query language Hibernate Query Language that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also

supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application. Step1: Create hibernate native sql for inserting data into database. Hibernate Native uses only the Hibernate Core for all its functions. The code for a class that will be saved to the database is displayed below: package hibernateexample; import javax.transaction.*; import org.hibernate.Transaction; import org.hibernate.*; import org.hibernate.criterion.*; import org.hibernate.cfg.*; import java.util.*; public class HibernateNativeInsert { public static void main(String args[]){ Session sess = null; try{ sess = HibernateUtil.currentSession(); Transaction tx = sess.beginTransaction(); Studentdetail student = new Studentdetail(); student.setStudentName("Amardeep Patel"); student.setStudentAddress("rohini,sec-2, delhi-85"); student.setEmail("amar@rediffmail.com"); sess.save(student); System.out.println("Successfully data insert in database"); tx.commit(); } catch(Exception e){ System.out.println(e.getMessage()); } finally{ sess.close(); } } } Step 2: Create session factory 'HibernateUtil.java'. Here is the code of session Factory: package hibernateexample; import java.sql.*; import org.hibernate.HibernateException;

import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import java.io.*; public class HibernateUtil { public static final SessionFactory sessionFact; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFact = new Configuration().configure().buildSessionFactory(); } catch(Throwable e) { System.out.println("SessionFactory creation failed." + e); throw new ExceptionInInitializerError(e); } } public static final ThreadLocal session = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session sess = (Session) session.get(); // Open a new Session, if this thread has none yet if(sess == null){ sess = sessionFact.openSession(); // Store it in the ThreadLocal variable session.set(sess); } return sess; } public static void SessionClose() throws Exception { Session s = (Session) session.get(); if (s != null) s.close(); session.set(null); } } Step 3: Hibernate native 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 "Studenetdetail.java": package hibernateexample; public class Studentdetail { private String studentName; private String studentAddress;

private String email; private int id; public String getStudentName(){ return studentName; } public void setStudentName(String studentName){ this.studentName = studentName; } public String getStudentAddress(){ return studentAddress; } public void setStudentAddress(String studentAddress){ this.studentAddress = studentAddress; } public String getEmail(){ return email; } public void setEmail(String email){ this.email = email; } public int getId(){ return id; } public void setId(int id){ this.id = id; } } Here is the output:

Hibernate Native SQL Example Native 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.*; /** * @author Deepak Kumar * * http://www.roseindia.net Hibernate Native Query Example * */ public class NativeQueryExample { 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(); /* 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); //Double [] amount = (Double []) query.uniqueResult(); 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); 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 ins mean amount: 592.1584 stdErr amount: 923.5714 Hibernate: 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 ins ID: 1 Name: Car Insurance ID: 2 Name: Life Insurance ID: 3 Name: Life Insurance ID: 4 Name: Car Insurance ...... ....... In this example you learned how to use Native Query with Hibernate. Associations and Joins This section includes a brief introduction about Associations and Joins along with examples. 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 Join

Hibernate'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"> <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 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub 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(); } 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_.id Dealer Name Product Name Price Computer Agrawal 23000.0 Keyboard Agrawal 1500.0 Computer Agrawal 100.0 Mobile Mohan 15000.0 PenDrive Mohan 200.0 Laptop Ritu 200.0 HardDisk Ritu 2500.0 Hibernate Aggregate Functions(Associations and Joins) This 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 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 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub 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_.name Dealer Name Product Name Price Agrawal Computer 23100.0 Ritu HardDisk 2500.0 Agrawal Keyboard 1500.0 Ritu Laptop 200.0 Mohan Mobile 15000.0 Mohan PenDrive 200.0 Hibernate Subqueries In 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 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 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub 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 Price Agrawal Computer 23000.0 Mohan Mobile 15000.0 Ritu HardDisk 2500.0 Hibernate Projections In this section, you will learn about the hibernate projections with an appropriate example. Projections: The package Criteria is used as a framework by the applications just to build the new kinds of projection. May be used by applications as a framework for building new kinds of Projection. In general Projection means to retrieve while in case of SQL Projection means "Select" clause. Most of the applications use the built-in projection types by means of the static factory methods of this class. Product.java package net.roseindia; public class Product { private int id; private String name; private double price; private Dealer dealer; private int did; public Product(String name, double price) { super(); // TODO Auto-generated constructor stub this.name = name; this.price = price; } public Product() { super(); // TODO Auto-generated constructor stub } public Dealer getDealer() { return dealer; } public void setDealer(Dealer dealer) { this.dealer = dealer; }

public double getDid() { return did; } public void setDid(int did) { this.did = did; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } ProjectionList: is the list of projection instances which are result of Query's object. Criteria API: enables us to specify criteria based on various. In the class projectionExample.java, 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. Then we obtain the criteria object simply by invoking the createCriteria() method of the Session's object. Now we create a projectionList object add the fields having properties "name" and "price". Set it to the Criteria object by invoking the setProjection() method and passing the projectList object into this method and then add this object into the List interface's list object and iterate this object list object to display the data contained in this object. projectionExample.java package net.roseindia; import java.util.Iterator;

import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; public class projectionExample { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try{ SessionFactory sfact = new Configuration().configure().buildSessionFactory(); sess = sfact.openSession(); Criteria crit = sess.createCriteria(Product.class); ProjectionList proList = Projections.projectionList(); proList.add(Projections.property("name")); proList.add(Projections.property("price")); crit.setProjection(proList); List list = crit.list(); Iterator it = list.iterator(); if(!it.hasNext()){ System.out.println("No any data!"); } else{ while(it.hasNext()){ Object[] row = (Object[])it.next(); for(int i = 0; i < row.length;i++){ System.out.print(row[i]); 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 this_.name as y0_, this_.price as y1_ from Product this_ Product Name Price Computer 23000.0 Mobile 15000.0 Laptop 200.0 Keyboard 1500.0 PenDrive 200.0 HardDisk 2500.0 Computer 100.0 Hibernate Projections (rowCount or countDistinct) In this section, you will learn about the hibernate projection with an example. Projection Interface: This is an interface that extends the Serializable. An object-oriented representation of a query result set projection in a Criteria query. Built-in projection types are provided by the Projections factory class. The Projection interface might be implemented by application classes that define custom projections. The following example to count the total number of rows and distinct rows to use the Projections.rowCount() and Projections.countDistinct() method. Table Name: Insurance

Here is the code of program: package roseindia.tutorial.hibernate; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Projections; public class hibernateProjectionExample { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try{ SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); crit.setProjection(Projections.rowCount()); List result = crit.list(); System.out.println("No. of rows: "+result); crit.setProjection(Projections.distinct(Projections.countDistinct("insuranceName"))); List distList = crit.list(); System.out.println("Distinct Count: "+ distList); } 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 y0_ from insurance this_ No. of rows: [7] Hibernate: select distinct count(distinct this_.insurance_name) as y0_ from insurance this_ Distinct Count: [5] Hibernate Projection Count In this section, you will learn to hibernate projection count. The example demonstrates the rowCount() method of the projection interface. 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> Here is the hibernate code: In the class projectionExample.java, 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. Then we obtain the criteria object simply by invoking the createCriteria() method of the Session's object. Now we set the number of rows count simply by calling the setProjection() method of the Criteria APIs and passing it the rowCount() method of the Projections interface. Then pass the reference of the Criteria object into the List interface object and finally iterate this object to count the number of rows. package net.roseindia; import java.util.Iterator; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.Projection; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; public class projectionCount { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory sfact = new Configuration().configure().buildSessionFactory(); sess = sfact.openSession(); Criteria crit = sess.createCriteria(Product.class); crit.setProjection(Projections.rowCount()); List list = crit.list(); Iterator it = list.iterator(); if (!it.hasNext()){ System.out.println("No any data!"); } else{ while(it.hasNext()){ Object count = it.next(); System.out.println("Row: " + count); } } } 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 y0_ from Product this_ Row: 7 Hibernate Projection Example (Sum) In this section, you will learn to hibernate aggregate function like: sum() using hibernate projection. The following example to calculate the sum of invested_amount to the Insurance table Table Name: Insurance

Here is the code of program: package roseindia.tutorial.hibernate; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; public class ProjectionExample1 { /** * @param args */

public static void main(String[] args) { // TODO Auto-generated method stub Session sess = null; try { SessionFactory fact = new Configuration().configure().buildSessionFactory(); sess = fact.openSession(); Criteria crit = sess.createCriteria(Insurance.class); ProjectionList proList = Projections.projectionList(); proList.add(Projections.sum("investementAmount")); crit.setProjection(proList); List sumResult = crit.list(); System.out.println("Total Invested Amount: " + sumResult); } 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 sum(this_.invested_amount) as y0_ from insurance this_ Total Invested Amount: [51400] Hibernate Mapping Files: In this section I will describe you the necessary Hibernate Mapping Files that is required to develop a hibernate application. Hibernate is very flexible O/R mapping tool. It works with many databases and it's very easy to move the application from one database to another database. Hibernate is configured at two levels: 1. Hibernate service 2. Persistence class configuration Hibernate Service configuration To configure the Hibernate service usually hibernate.cfg.xml file is used. The default name of configuration file is hibernate.cfg.xml, but it is also possible to give different name to the configuration file. While configuring the Hiberbate Service we provide database connection url and passwords. We also provide different caching level for the application performance. Here is the code of hibernate.cfg.xml file used in our example application <?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatemappings</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</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="employee.hbm.xml"/> </session-factory> </hibernate-configuration> Configuration parameter description: hibernate.connection.driver_class is used to specify the JDBC Driver class hibernate.connection.url is database connection url hibernate.connection.username is username to access database hibernate.connection.password is the password to connect to the database dialect property is used to specify the database dialect. Here in this case it is org.hibernate.dialect.MySQLDialect. You can read more about hibernate dialect here. Configuring the Persistence class Usually <persistence-object>.hbm.xml file is used to configure the Persistence object. Here is the example employee.hbm.xml configuration used in our application. employee.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="roseindia.Employee" table="employee"> <id name="empId" type="int" column="Emp_id" unsaved-value="0"> <generator class="increment"/> </id> <property name="empName" type="java.lang.String" column="Emp_name" not-null="true" length="50" /> <property name="empSal" type="java.lang.Double" column="Emp_sal" not-null="true" /> </class>

</hibernate-mapping> In nutshell we need one configuration file and one hibernate mapping files to develop the application. These are: hibernate.cfg.xml and <persistence-object>.hbm.xml Hibernate Relationships - Hibernate Relationships mapping example In this tutorial we will learn how to create relationships among the Entity. We will learn Hibernation Relationships mapping in detail with the example code. You can download the code and then try on your computer. The Eclipse IDE can be used to run the Hibernate Relationships examples. You can easily import the project into Eclipse IDE. The relational databases support one-to-one, one-to-many, many-to-many and many-to-one relationships. We can simulate the all these relationships in our Java. With the help of Hibernate relationships we can define these associations among the persistence unit and use in the Java program. With the help of annotations and the xml meta-data once can create the Entity relationships. Hibernate will then use the relationships metadata to persist the data into database tables. For example you can create the object of master entity and add the child entity into the master entity and then save the master entity. This will save master and child entity into the database. The Java 5 annotation and xml meta-data can be use to define the relationships among the persistence classes. Let's learn the Hibernate annotations in details. Hibernate annotations using xml files Hibernate Relationships - Settingup database In this section we will setup the database for the tutorial. We are using MySQL database for this tutorial. You can download MySQL and install on your computer. More information on installing MySQL is available at http://www.roseindia.net/mysql/mysql5/Installing-MySQLon-Windows.shtml. You can use command line tool or any MySQL GUI to connect view the tables, structure and data in the MySQL database. Here is small tutorial on using MySQL client http://www.roseindia.net/mysql/mysql.shtml. Now let's setup the database and create the MySQL schema. We will use the Hibernate hbm2ddl utility to create/update the table structure at run time. Here is the property defined into hibernate.cfg.xml file: <property name="hibernate.hbm2ddl.auto">update</property> The above utility is good and can be used at development time, in production application you must set the value to none. Use this utility carefully otherwise it will drop your existing tables along with the data. Step1: Create MySQL database using the following command: create database hibrel;

In this example we will use the database called hibrel to run the examples. 1. Hibernate service 2. Persistence class configuration Step 2: Download the source code of examples discusses in the tutorial by clicking here HibRelationships.zip. Open the Eclipse IDE and create a new project from the downloaded source. We have included all the jar files required to run the example. Step 3: Open hibernate.cfg.xml file and change the database connection url, password and user name to connect to database. <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibrel</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> While configuring the Hiberbate Service we provide database connection url and passwords. We also provide different caching level for the application performance. Here is the code of hibernate.cfg.xml file used in our example application <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibrel</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</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="Employee.hbm.xml"/> <mapping resource="Group.hbm.xml"/> <mapping resource="author.hbm.xml"/> <mapping resource="book.hbm.xml"/> </session-factory> </hibernate-configuration> Step 4: To create the database schema, open OneToManyRelation.java in the Eclipse and right click and select Run As--> Java application. Hibernate will create required tables for the tutorial. The Eclipse should display the following output: log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly. Hibernate: insert into gropuptable (name) values (?) Hibernate: select max(id) from story Group id:1 Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: update story set parent_id=?, idx=? where id=? Hibernate: update story set parent_id=?, idx=? where id=? Hibernate: update story set parent_id=?, idx=? where id=? Hibernate: update story set parent_id=?, idx=? where id=? Now check your database and following tables should present: 1. authorauthor_book 2. book 3. employeeemployee_address 4. gropuptable 5. story Usually <persistence-object>.hbm.xml file is used to configure the Persistence object. Here is the example employee.hbm.xml configuration used in our application. Here is the script to create database manually: CREATE TABLE `author` ( `id` int(11) NOT NULL, `authorName` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM; CREATE TABLE `book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `bookName` varchar(250) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM; CREATE TABLE `author_book` ( `authorId` int(11) NOT NULL, `bookId` int(11) NOT NULL, PRIMARY KEY (`bookId`,`authorId`), KEY `FK2A7A111DB63F85B3` (`bookId`), KEY `FK2A7A111DFC08F7` (`authorId`) ) ENGINE=MyISAM CREATE TABLE `employee` ( `employee_id` int(11) NOT NULL AUTO_INCREMENT, `employee_name` varchar(50) NOT NULL, PRIMARY KEY (`employee_id`) ) ENGINE=MyISAM;

CREATE TABLE `employee_address` ( `id` int(11) NOT NULL AUTO_INCREMENT, `address` varchar(255) NOT NULL, `country` varchar(100) NOT NULL, `emp_id` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM; CREATE TABLE `gropuptable` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM; CREATE TABLE `story` ( `id` int(11) NOT NULL, `info` varchar(255) DEFAULT NULL, `parent_id` int(11) DEFAULT NULL, `idx` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `FK68AF8F58984AF09` (`parent_id`) ) ENGINE=MyISAM; In next section we will learn how to create and run the one-to-one mapping in Hibernate. Hibernate One-to-one Relationships Hibernate One-to-one Relationships - One to one relationships example using xml metadata This section we will see the the structure of Entity classes and the one-to-one mapping tags in the .hbm.xml file. We will also run the example and see the data into database. One-to-One Relationships In case of one-to-one relationships, each row in table A linked to only one row in table B. Here we will implement one-to-one relationship between two entries Employee and EmployeeAddress. We are using two tables employee and employee_address and java entities Employee and EmployeeAddress maps respectively. Here is the ER diagram

Java Persistence Objects:

The code for Employee.java is given below: package roseindia; public class Employee { private int id; private String name; private EmployeeAddress address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public EmployeeAddress getAddress() { address.setEmpid(getId()); return address; } public void setAddress(EmployeeAddress address) { this.address = address; } } The code for EmployeeAddress.java is given below: package roseindia; public class EmployeeAddress { private int id; private int empid; private String address; private String country; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getEmpid() {

return empid; } public void setEmpid(int empid) { this.empid = empid; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } Mapping xml file (Employee.hbm.xml): This file contains the mapping for both the entities Employee and EmployeeAddress. <?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.Employee" table="employee"> <id name="id" type="int" column="employee_id" > <generator class="native"/> </id> <property name="name" type="java.lang.String" column="employee_name" not-null="true" length="50" /> <one-to-one name="address" class="roseindia.EmployeeAddress" property-ref="empid" cascade="all"/> </class> <class name="roseindia.EmployeeAddress" table="employee_address"> <id name="id" type="int" column="id" > <generator class="native"/> </id>

<property name="address" type="java.lang.String" column="address" not-null="true" length="255" /> <property name="country" type="java.lang.String" column="country" not-null="true" length="100" /> <property name="empid" type="int" column="emp_id" not-null="true" length="100" /> </class> </hibernate-mapping> The following mapping tag defines the one-to-one mapping between Employee and EmployeeAddress entities. <one-to-one name="address" class="roseindia.EmployeeAddress" property-ref="empid" cascade="all"/> Here empid variable is defined in EmployeeAddress entity which is used for defining the relationships. Running the Program: To run and test the program you have to execute the OneToOneRelation.java. Here is the full code of OneToOneRelation.java file: package roseindia; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class OneToOneRelation { public static void main(String[] args) {

SessionFactory sessFact=null; Session sess=null; try{ sessFact=new Configuration().configure().buildSessionFactory(); sess=sessFact.openSession(); System.out.println("sess:"+sess); //Create Customer Object Employee emp = new Employee(); emp.setName("Deepak"); //Create address object EmployeeAddress address = new EmployeeAddress(); //Set some values address.setAddress("Delhi"); address.setCountry("India"); emp.setAddress(address); Transaction tr = sess.beginTransaction(); sess.save(emp); tr.commit(); System.out.println("Done"); } catch (HibernateException he){ System.out.println(he.getMessage()); } finally{ //SessionFactory close sessFact.close(); //Session close sess.close(); } } } The above code is self explanatory, we are creating the objects of Employee and EmployeeAddress and filling the values. Then we are setting the address object into Employee object and finally calling the sess.save(emp) method. On calling the save() method on the Session object, hibernate reads the state of the objects and persists the data into database.

You can run the example in eclipse and you should get the following output: log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. sess:SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertio ns=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]]) Hibernate: insert into employee (employee_name) values (?) Hibernate: insert into employee_address (address, country, emp_id) values (?, ?, ?) Done In this section we learned about the one-to-one relationships in Hibernate. In next section we will learn how to create and run the one-to-many mapping in Hibernate. Hibernate One-to-many Relationships Hibernate One-to-many Relationships - One to many example code in Hibernate using the xml file as metadata. Here you will learn one-to-many relationships developed using the hmb.xml file. The one-tomany tag is used to define the relationships. One-to-Many Relationships In case of one-to-many relationships, each row in table A linked to multiple rows in table B. Here we will implement one-to-many relationship between two entries Group and Story. There exists multiple stories under a group. We are using two tables grouptable and story and java entities Group and Story maps respectively. Here is the ER diagram

Java Persistence Objects: The code for Group.java is given below: package roseindia; import java.util.List; public class Group {

private int id; private String name; private List stories; public Group(){ } public Group(String name) { this.name = name; } 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 sl) { stories = sl; } public List getStories() { return stories; } } The code for Story.java is given below: package roseindia; public class Story { private int id; private String info;

private Group group; public Story(){ } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } 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; } } Mapping xml file (Group.hbm.xml): This file contains the mapping for both the entities Stroy and Group which maps with the tables gropuptable and story respectively. <?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.Group" table="gropuptable"> <id name="id" type="int" column="id">

<generator class="native" /> </id> <property name="name" type="java.lang.String" column="name" length="50" /> <list name="stories" cascade="all"> <key column="parent_id" /> <index column="idx" /> <one-to-many class="roseindia.Story" /> </list> </class> <class name="roseindia.Story" table="story"> <id name="id" type="int" column="id"> <generator class="increment" /> </id> <property name="info" type="java.lang.String" column="info" length="255" /> <many-to-one name="group" class="roseindia.Group" column="parent_id" /> </class> </hibernate-mapping> The following mapping tag defines the one-to-many mapping between Group and Story entities. <list name="stories" cascade="all"> <key column="parent_id" /> <index column="idx" /> <one-to-many class="roseindia.Story" /> </list> In Group.java we have stories variable of the list type, so we have used the <list../> tag here. The <one-to-many ../> specifies the one to many relationships to Story entity. Running the Program: To run and test the program you have to execute the OneToManyRelation.java. Here is the full code of OneToManyRelation.java file: package roseindia; import java.awt.Stroke; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration;

//Goups and Stories public class OneToManyRelation { // Group and Multiple Stories public static void main(String[] args) { SessionFactory sessFact = null; Session session = null; try { sessFact = new Configuration().configure().buildSessionFactory(); session = sessFact.openSession(); Transaction tr = session.beginTransaction(); // Group Object Group group = new Group("Java Group 2"); // Array list to hold stories ArrayList list = new ArrayList(); // Create Stories Story javaHistory = new Story(); javaHistory.setInfo("Java History"); list.add(javaHistory); // Create Stories Story javaPlatform = new Story(); javaPlatform.setInfo("Java Platforms"); list.add(javaPlatform); // Create Stories Story javaNews = new Story(); javaNews.setInfo("Java News"); list.add(javaNews); // Create Stories Story jeeNews = new Story(); jeeNews.setInfo("JEE News"); list.add(jeeNews); // Add the list to Group object group.setStories(list); // Save group

session.save(group); // Print the generated group id System.out.println("Group id:" + group.getId()); /* * * //Load the group class Group g = (Group) * session.load(Group.class, 1); System.out.println("Group Name:" + * g.getName()); * * List listStories = g.getStories(); Iterator storiesIter = * listStories.iterator(); while(storiesIter.hasNext()) { Story * story = (Story)storiesIter.next(); * System.out.println("Story Info:" + story.getInfo()); } */ tr.commit(); } catch (HibernateException he) { System.out.println(he.getMessage()); } finally { // Session close session.close(); // SessionFactory close sessFact.close(); } } } The above code is self explanatory, we are creating the objects of Group: // Group Object Group group = new Group("Java Group 2"); Then set the author name: The create ArrayList object set and add many Story objects: // Array list to hold stories ArrayList list = new ArrayList(); // Create Stories Story javaHistory = new Story(); javaHistory.setInfo("Java History"); list.add(javaHistory);

// Create Stories Story javaPlatform = new Story(); javaPlatform.setInfo("Java Platforms"); list.add(javaPlatform); // Create Stories Story javaNews = new Story(); javaNews.setInfo("Java News"); list.add(javaNews); // Create Stories Story jeeNews = new Story(); jeeNews.setInfo("JEE News"); list.add(jeeNews); Finally add the book set to the group object and save the group object: // Add the list to Group object group.setStories(list); // Save group session.save(group); Here is output of the program when executed in Eclipse IDE. log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. Hibernate: insert into gropuptable (name) values (?) Hibernate: select max(id) from story Group id:2 Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: insert into story (info, parent_id, id) values (?, ?, ?) Hibernate: update story set parent_id=?, idx=? where id=? Hibernate: update story set parent_id=?, idx=? where id=? Hibernate: update story set parent_id=?, idx=? where id=? Hibernate: update story set parent_id=?, idx=? where id=? In this section we learned about the one-to-many relationships in Hibernate. In next section we will learn how to create and run the many-to-many mapping in Hibernate. Many to many relationships is interesting as one extra table is needed to persist the relationship. Hibernate Many-to-many Relationships Hibernate Many-to-many Relationships - Many to many example in Hibernate. In this example we have used xml metadata. Now we will learn many-to-many relationships. Let's try many-to-many example. The manyto-many tag is used to define the relationships. The extra table is required in the database to

persist the relationship, we will use author_book table to persist the relationship between Author and Book entities. Let's get started with Many-to-many relationship. Many-to-Many Relationships In case of many-to-many relationships, each row in table A linked to multiple rows in table B and vice versa. Here we will implement many-to-many relationship between two entries Author and Book. A book might be authored by multiple author and one author might author many books. We are using two tables author and book and java entities Author and Book maps respectively. Here is the ER diagram

Java Persistence Objects: The code for Author.java is given below: package roseindia; import java.util.Set; public class Author { private int id; private String authorName; private Set books; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id;

} /** * @return the authorName */ public String getAuthorName() { return authorName; } /** * @param authorName the authorName to set */ public void setAuthorName(String authorName) { this.authorName = authorName; } public Set getBooks() { return books; } public void setBooks(Set books) { this.books = books; } } The code for Book.java is given below: package roseindia; import java.util.Set; public class Book { private int id; private String bookName; private Set authors; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) {

this.id = id; } /** * @return the bookName */ public String getBookName() { return bookName; } /** * @param bookName the bookName to set */ public void setBookName(String bookName) { this.bookName = bookName; } /** * @return the books */ public Set getAuthors() { return authors; } public void setAuthors(Set authors) { this.authors = authors; } } Mapping xml file (author.hbm.xml: This file contains the mapping for both the entities Author and Book which maps with the tables author and group respectively. <?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.Author" table="author"> <id name="id" type="int" column="id" unsaved-value="0"> <generator class="increment" /> </id> <property name="authorName" type="java.lang.String" column="authorName" not-null="true" length="50" /> <set name="books" table="author_book" cascade="all"> <key column="authorId" />

<many-to-many column="bookId" class="roseindia.Book" /> </set> </class> <class name="roseindia.Book" table="book"> <id name="id" type="int" column="id" unsaved-value="0"> <generator class="native" /> </id> <property name="bookName" type="java.lang.String" column="bookName" not-null="true" length="250" /> <set name="authors" table="author_book" cascade="all"> <key column="bookId" /> <many-to-many column="authorId" class="roseindia.Author" /> </set> </class> </hibernate-mapping> The following mapping tag defines the many-to-many mapping between Author and Book entities from the Author entity. <set name="books" table="author_book" cascade="all"> <key column="authorId" /> <many-to-many column="bookId" class="roseindia.Book" /> </set> Here table="author_book" is the name of table which is used to define the relationships between the two entities and authorId is the foreign key of table author. Similarly bookId is the foreign key of book table. Following code defines the many-to-many relationships from the Book entity. <set name="authors" table="author_book" cascade="all"> <key column="bookId" /> <many-to-many column="authorId" class="roseindia.Author" /> </set> In Group.java we have stories variable of the list type, so we have used the <list../> tag here. The <one-to-many ../> specifies the one to many relationships to Story entity. Running the Program: To run and test the program you have to execute the ManyToManyRelation.java. Here is the full code of ManyToManyRelation.java file: package roseindia; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set;

import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class ManyToManyRelation { public static void main(String[] args) { SessionFactory sessFact = null; Session session = null; try { sessFact=new Configuration().configure().buildSessionFactory(); session=sessFact.openSession(); Transaction tr = session.beginTransaction(); //One author and may books Author author = new Author(); author.setAuthorName("John"); Author author2 = new Author(); author2.setAuthorName("Deepak"); Set bookSet = new HashSet(); //Solaris Book bookSolaris = new Book(); bookSolaris.setBookName("Solaris in a week"); bookSet.add(bookSolaris); //Linux Book bookLinux = new Book(); bookLinux.setBookName("Linux in a week"); bookSet.add(bookLinux); //Oracle Book bookOracle = new Book(); bookOracle.setBookName("Oracle in a week"); bookSet.add(bookOracle);

//Add book set to the author object author.setBooks(bookSet); session.save(author);

/* Book book = new Book(); book.setBookName("Phoenix"); Author author = new Author(); Author author1 = new Author(); Author author2 = new Author(); Author author3 = new Author(); author.setAuthorName("Clifford Geertz"); author1.setAuthorName("JP Morgenthal"); author2.setAuthorName("Yaswant Kanitkar"); author3.setAuthorName("Phola Pandit"); Set authorSet = new HashSet(); authorSet.add(author); authorSet.add(author1); authorSet.add(author2); authorSet.add(author2); book.setAuthors(authorSet); session.save(book); */

/* //One author and may books Author author = new Author(); author.setAuthorName("John"); Author author2 = new Author(); author2.setAuthorName("Deepak"); Set bookSet = new HashSet(); //Solaris

Book bookSolaris = new Book(); bookSolaris.setBookName("Solaris in a week"); bookSet.add(bookSolaris); //Linux Book bookLinux = new Book(); bookLinux.setBookName("Linux in a week"); bookSet.add(bookLinux); //Oracle Book bookOracle = new Book(); bookOracle.setBookName("Oracle in a week"); bookSet.add(bookOracle); //Add book set to the author object author.setBooks(bookSet); author2.setBooks(bookSet); session.save(author); session.save(author2); Set authors = new HashSet(); authors.add(author); authors.add(author2); //One Book and may authors //Create Book Book javaBook = new Book(); javaBook.setBookName("Java in a week"); javaBook.setAuthors(authors); //Save session.save(javaBook); */ //Create author set //Set authors = new HashSet();

/* Author JohnAuth = new Author(); JohnAuth.setAuthorName("John"); authors.add(JohnAuth); Author deepakAuth = new Author(); deepakAuth.setAuthorName("Deepak"); authors.add(deepakAuth); Author manojAuth = new Author(); manojAuth.setAuthorName("Manoj"); authors.add(manojAuth); //Create and add authors //Add author set to book javaBook.setAuthors(authors); //Save session.save(javaBook); */ /* //Displaying all the books for the Author 2 Author a = (Author)session.load(Author.class, 2); Set book = a.getBooks(); System.out.println(a.getAuthorName()); System.out.println("total=" + book.size()); Iterator iter = book.iterator(); while (iter.hasNext()) { Book b = (Book)(iter.next()); System.out.println(b.getBookName()); } */ tr.commit(); System.out.println("Done"); } catch(HibernateException He){ System.out.println(He.getMessage()); } finally{ session.close();

} } } The above code is self explanatory, we are creating the objects of Author: Author author = new Author(); Then set the author name: author.setAuthorName("John"); The create Book set and add many books: Set bookSet = new HashSet(); //Solaris Book bookSolaris = new Book(); bookSolaris.setBookName("Solaris in a week"); bookSet.add(bookSolaris); //Linux Book bookLinux = new Book(); bookLinux.setBookName("Linux in a week"); bookSet.add(bookLinux); //Oracle Book bookOracle = new Book(); bookOracle.setBookName("Oracle in a week"); bookSet.add(bookOracle); Finally add the book set to the author object and save the author: //Add book set to the author object author.setBooks(bookSet); session.save(author); The above code will save author and the books authored by the author. You can also uncomment the comment the code in ManyToManyRelation.java and try more examples such as many Authors authoring the same book. Here is output of the program when executed in Eclipse IDE. log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. Hibernate: select max(id) from author Hibernate: insert into author (authorName, id) values (?, ?) Hibernate: insert into book (bookName) values (?) Hibernate: insert into book (bookName) values (?) Hibernate: insert into book (bookName) values (?) Hibernate: insert into author_book (authorId, bookId) values (?, ?) Hibernate: insert into author_book (authorId, bookId) values (?, ?) Hibernate: insert into author_book (authorId, bookId) values (?, ?) Done

In this section we learned about the Many-to-one relationships in Hibernate. Hibernate Many-to-one Relationships Hibernate Many-to-one Relationships - Many to one relationships example using xml meta-data This current example demonstrates the use of Many to one relationships. We will use .hbm.xml file to map the relatioships. We will also run the example and load the data from database. Many-to-One Relationships A many-to-one relationship is where one entity contains values that refer to another entity (a column or set of columns) that has unique values. In relational databases, these many-to-one relationships are often enforced by foreign key/primary key relationships, and the relationships typically are between fact and dimension tables and between levels in a hierarchy. In this example multiple stories (Java History, Java Platform, Java News and JEE News) are linked to the Java Group 2 (whose primary key is 1)

Here we will implement Many-to-one relationship between two entries Group and Story. You can check the Group.java, Story.java and Group.hbm.xml file in our one-to-many example section. Story Entity: In the Entity Story.java we have to define Group object and getter and setters for the same: private Group group; public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } Explanation of Hibernate mapping: The following mapping is used to define the many-to-one relationships: <many-to-one name="group" class="roseindia.Group" column="parent_id" /> To run the example you can execute ManyToOneRelation.java. Here is the code of ManyToOneRelation.java class:

/** * */ package roseindia; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class ManyToOneRelation { public static void main(String[] args) { SessionFactory sessFact = null; Session sess = null; try { sessFact=new Configuration().configure().buildSessionFactory(); sess=sessFact.openSession(); Story story = (Story)sess.load(Story.class, 3); Group group = story.getGroup(); System.out.println("Group Name: "+group.getName()); } catch (HibernateException he){ System.out.println(he.getMessage()); } finally{ //SessionFactory close sessFact.close(); //Session close sess.close(); } } } In the above code we have loaded the Story entity whose primary key is 3, and then retrieved the parent Group. We have also printed the name of story. If you run the example in Eclipse you should get the following output: og4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly.

Hibernate: select story0_.id as id3_0_, story0_.info as info3_0_, story0_.parent_id as parent3_3_0_ from story story0_ where story0_.id=? Hibernate: select group0_.id as id2_0_, group0_.name as name2_0_ from gropuptable group0_ where group0_.id=? Group Name: Java Group 2 Congratulations you have learned all the types on relations in Hibernate. To recap you have learned: 1. One-to-one mapping 2. One-to-many mapping 3. Many-to-many mapping 4. Many-to-one mapping Hibernate Annotations Note:- This tutorial covers only the Annotations part. The reader must have hands on experience before starting this tutorial. Introduction:- Hibernate needs a metadata to govern the transformation of data from POJO to database tables and vice versa. Most commonly XML file is used to write the metadata information in Hibernate. The Java 5 (Tiger) version has introduced a powerful way to provide the metadata to the JVM. The mechanism is known as Annotations. Annotation is the java class which is read through reflection mechanism during the runtime by JVM and does the processing accordingly. The Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development. This also reduces the management of different files for the metadata and java code. Prerequisite for setting the project :1. Make sure you have Java 5.0 or higher version . 2. You should have Hibernate Core 3.2.0GA and above. 3. Download and add the Hibernate-Annotations jar file in the project workspace. The First Application :Let us assume we have a table Employee which has only two columns i.e ID and Name. In hibernate core to achieve the mapping for the above employee table the user should create the following files :1. Utility file for configuring and building the session factory. 2. Hibernate.cfg.xml or any other Datasource metadata file 3. Employee POJO object. 4. employee.hbm.xml file. (This file is now omitted for the ) 5. Real application file which has the actual logic manipulate the POJO Note:- Annotations are only the step to remove the hbm.xml file so all the steps remain same only some modifications in some part and adding the annotation data for the POJO.

Please note that coming example will use the Employee table from the database. The SQL query to create the employee table is as follows :Create table Employee( ID int2 PRIMARY KEY, NAME nvarchar(30) ); Step 1:- Creating Utility Class :- The following is the code given for the utility class for sessionFactory:package net.roseindia; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } If you see the only change in the file for the annotations is we use AnnotationConfiguration() class instead of the Configuratio() class to build the sessionFactory for the hibernate. Step 2: - The Hibernate.cfg.xml is the configuration file for the datasource in the Hibernate world. The following is the example for the configuration file. <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">none</property> <mapping class="com.roseindia.Employee"/> </session-factory> </hibernate-configuration> The only change is, we are now telling the compiler that instead of any resource get the metadata for the mapping from the POJO class itself like in this case it is net.roseindia.Employee . Note:- Using annotations does not mean that you cannot give the hbm.xml file mappng. You can mix annotations and hbm.xml files mapping for different Pojo but you cannot mix the mappings for the same Pojo in both ways. This we will discuss further. Step 3: -The major changes occurred only in the POJO files if you want to use the annotations as this is the file which will now contain the mapping of the properties with the database. The following is the code for the Employee POJO. package net.roseindia; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "employee") public class Employee implements Serializable { public Employee() {

} @Id @Column(name = "id") Integer id; @Column(name = "name") String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } In the EJB word the entities represent the persistence object. This can be achieved by @Entity at the class level. @Table(name = "employee") annotation tells the entity is mapped with the table employee in the database. Mapped classes must declare the primary key column of the database table. Most classes will also have a Java-Beans-style property holding the unique identifier of an instance. The @Id element defines the mapping from that property to the primary key column. @Column is used to map the entities with the column in the database. Step 4: -The following code demonstrate storing the entity in the database. The code is identical as you have used in theHibernate applications. package net.roseindia; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; public class Example1 { /** * @param args

*/ public static void main(String[] args) throws Exception { /** Getting the Session Factory and session */ SessionFactory session = HibernateUtil.getSessionFactory(); Session sess = session.getCurrentSession(); /** Starting the Transaction */ Transaction tx = sess.beginTransaction(); /** Creating Pojo */ Employee pojo = new Employee(); pojo.setId(new Integer(5)); pojo.setName("XYZ"); /** Saving POJO */ sess.save(pojo); /** Commiting the changes */ tx.commit(); System.out.println("Record Inserted"); /** Closing Session */ session.close(); } } Output :Record. Inserted. Conclusion:The above article shows the basic configurations for the Hibernate annotations. The above example will only add one record in the Database using the hibernate annotations. In the coming article we will discuss about the various available annotations in the JPA and the also the examples demonstrate how to use the annotations for mapping all the hibernate POJO to the database tables.

You might also like