What is Hibernate?
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.
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 provide the ability to the user to execute more than one database statements at a time.
Transaction management service provide the ability to the user to execute more than one database statements at a time.
· Object relational mapping:
Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the hibernate is used to select, insert, update and delete the records form the underlying table. When we pass an object to a Session.save() method, Hibernate reads the state of the variables of that object and executes the necessary query.
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.
Configuring Hibernate
In this application Hibernate provided connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment.
Here is the code:
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 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 com.tutorial.hibernate;
/**
* @author Roy
*
* 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;
}
}
/**
* @author Roy
*
* 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:
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.
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)
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)
package com.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author Roy
*
* 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
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author Roy
*
* 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
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set
values in it by reading them from form objectsession =sessionFactory.openSession();
//Create new instance of Contact and set
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(3);
contact.setFirstName("Biswajit");
contact.setLastName("Roy");
contact.setEmail("biswajitroy04@gmail.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();
}
}
}
Understanding Hibernate O/R Mapping
Now let's understand the each component of the mapping file.
To recall here is the content of contact.hbm.xml:
Hibernate mapping documents are simple xml documents. Here are important elements of the mapping file:
element
The first or root element of hibernate mapping document iselement. Between the <hibernate-mapping> tag class element(s) are present.
-
element
Theelement 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 element, several mappings are possible.
-
element
Theelement in unique identifier to identify and object. In fact element map with the primary key of the table. In our code :
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.
element
The
* 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.
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 element
The element
This is the optional element under element. The 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 element is used to pass the parameter (s) to the class. Here is the example of generator element from our first application:
Here are the list of some commonly used generators in hibernate:
Generator | Description |
increment | It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment. |
identity | It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int. |
sequence | The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int |
hilo | The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection. |
seqhilo | The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of 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 string of hexadecimal digits of length 32. |
guid | It uses a database-generated GUID string on MS SQL Server and MySQL. |
native | It picks identity, sequence or hilo depending upon the capabilities of the underlying database. |
assigned | lets the application to assign an identifier to the object before save() is called. This is the default strategy if no |
select | retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value. |
foreign | uses the identifier of another associated object. Usually used in conjunction with a |
Using Hibernate to generate id incrementally
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
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".
Book.java is our POJO class which is to be persisted to the database table "book".
* @author Roy
*
* Java Class to map to the database Book table
*/
package com.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
Add the following mapping code into the contact.hbm.xml file
Write the client program and test it out
Here is the code of our client program to test the application.
Here is the code of our client program to test the application.
* @author Roy
*
* Example to show the increment
class of hibernate
generator element to
* automatically generate
the primay key
*/
package com.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
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 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
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());
}
}
}
Hibernate Delete Query
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 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"
package com.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 Roy
*
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());
}
}
}
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.
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:
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.
Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying database supports it.
HQL from clause Example
from Insurance insurance
Here is the full code of the from clause example:
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Roy
*
* 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{
}
}
}
Hibernate Select Clause
Select insurance.lngInsuranceId, insurance.insuranceName, insurance.investementAmount, insurance.investementDate from Insurance insurance
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 com.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Roy
*
* HQL Select Clause Example
*/
public class SelectClauseExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Roy
*
* 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
SessionFactory sessionFactory = new
Configuration().configure()
.buildSessionFactory();
session =sessionFactory.openSession();
//Create Select Clause HQL
String SQL_QUERY ="Select insurance.
.buildSessionFactory();
session =sessionFactory.openSession();
//Create Select Clause HQL
String SQL_QUERY ="Select insurance.
lngInsuranceId,insurance.insuranceName," +
"insurance.investementAmount,insurance.
investementDate from Insurance insurance";"insurance.investementAmount,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{
}
}
}
HQL Where Clause Example
from Insurance where lngInsuranceId='1'
Where Clause can be used with or without Select Clause. Here the example code:
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Roy
*
* 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{
}
}
}
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:
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Roy
*
* 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 {
}
}
}
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:
import org.hibernate.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;
/**
* @author Roy
*
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 {
}
}
}
No comments:
Post a Comment