Hibernate Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

Hibernate is an Object-Relational Mapping (ORM) solution for JAVA.

It is an open
source persistent framework created by Gavin King in 2001.

Hibernate maps Java classes to database tables and from Java data types to SQL
data types and relieves the developer from 95% of common data persistence
related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all
the works in persisting those objects based on the appropriate O/R mechanisms
and patterns.
The above diagram shows that Hibernate is using the database and configuration
Data(Hibernate.properties and XML Mapping) to provide persistence services( and
persistent objects) to the application
Reg.hbm.xml
RegisterForm.jsp Studentpojo.java Reg.cfg.xml

Main Controller
cfg file loader
public class StudentPojo
{
private int roll;
private String firstname,lastname;

public int getRoll() {


return roll;
}

public void setRoll(int roll) {


this.roll = roll;
}

public String getFirstname() {


return firstname;
}

public void setFirstname(String firstname) {


this.firstname = firstname;
}

public String getLastname() {


return lastname;
}

public void setLastname(String lastname) {


this.lastname = lastname;
Create the mapping file for Persistent class

The mapping file name conventionally, should be class_name.hbm.xml. There are many elements
of the mapping file.

hibernate-mapping : It is the root element in the mapping file that contains all the mapping
elements.

class : It is the sub-element of the hibernate-mapping element. It specifies the Persistent class.

id : It is the subelement of class. It specifies the primary key attribute in the class.

generator : It is the sub-element of id. It is used to generate the primary key. There are many
generator classes such as assigned, increment, hilo, sequence, native etc. We will learn all the
generator classes later.

property : It is the sub-element of class that specifies the property name of the Persistent class.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">

<hibernate-mapping>
<class name="pojo.StudentPojo" table=“student">
<id name="id">
<generator class="assigned"></generator>
</id>

<property name="firstName"></property>
<property name="lastName"></property>

</class>

</hibernate-mapping>
Configuration

Configuration is a class which is present in org.hibernate.cfg package. It


activates Hibernate framework. It reads both configuration file and mapping files.

It activate Hibernate Framework Configuration cfg=new Configuration();

It read both cfg file and mapping files cfg.configure();

It checks whether the config file is syntactically correct or not.

If the config file is not valid then it will throw an exception. If it is valid then it
creates a meta-data in memory and returns the meta-data to object to represent
the config file.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demo2</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">12345</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping resource="hibernate.hbm.xml"/>

</session-factory>
</hibernate-configuration>
SessionFactory

SessionFactory is an Interface which is present in org.hibernate package and it is used to create


Session Object.
It is immutable and thread-safe in nature.buildSessionFactory() method gathers the meta-data
which is in the cfg Object. From cfg object it takes the JDBC information and create a JDBC
Connection. SessionFactory factory=cfg.buildSessionFactory();

The SessionFactory object is used by all the threads of an application. It is a thread safe object.
One SessionFactory object is created per database. Multiple SessionFactory objects (each
requiring a separate configuration) are created when connecting to multiple databases. The
SessionFactory can also provide caching of persistent objects.
Session

Session is an interface which is present in org.hibernate package. Session object


is created based upon SessionFactory object i.e. factory.

It opens the Connection/Session with Database software through Hibernate


Framework.
It is a light-weight object and it is not thread-safe.

Session object is used to perform CRUD operations.

Session session=factory.openSession();
Transaction:

Transaction object is used whenever we perform any operation and based upon
that operation there is some change in database.

Transaction object is used to give the instruction to the database to make the
changes that happen because of operation as a permanent by using commit()
method.

Transaction tx = session.beginTransaction();

tx.commit();
1. C (CREATE)
2. R(READ)
3. U(UPDATE)
4. D(DELETE)

For inserting data into the table.

1. Save() method:-- Save method return primary key after successful insertion.

2. persist() method:-- Its does not return anything. Its return type is void.

3. saveOrUpdate():- Its does not return anything. . Its return type is void. It will update existing data based
on ID.
Hibernate Query Language (HQL) is an object-oriented query language, similar to
SQL, but instead of operating on tables and columns, HQL works with persistent
objects and their properties.

HQL queries are translated by Hibernate into conventional SQL queries, which in
turns perform action on database.

Although you can use SQL statements directly with Hibernate using Native SQL,
but I would recommend to use HQL whenever possible to avoid database portability.
 HQL is similar to SQL and is also case insensitive.

 HQL and SQL both fire queries in a database. In the case of HQL queries are in the
form of objects that are translated to SQL queries in the target database.

 SQL works with tables and columns to manipulate the data stored in it.

 HQL works with classes and their properties to finally be mapped to a table
structure.

 HQL supports concept like polymorphism, inheritance, association etc. It is a


powerful and easy-to-learn language that makes SQL object oriented.

 SQL lets you modify the data through insert, update and delete queries.

 You can add tables, procedures, or view to your database. The permissions on these
Advantage of HQL

There are many advantages of HQL. They are as follows:

1. database independent
2. supports polymorphic queries
3. easy to learn for Java Programmer

Note:-

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties
like table and column names are case sensitive in HQL.
Query:

Query is an interface that present inside org.hibernate package.

A Query instance is obtained by calling Session.createQuery().

This interface exposes some extra functionality beyond that provided by


Session.iterate() and Session.find():

A particular page of the result set may be selected by calling setMaxResults(),


setFirstResult().

Named query parameters may be used.

Query query=session.createQuery();
It is an object oriented representation of Hibernate Query. The object of Query can be obtained by calling
the createQuery() method Session interface.

The query interface provides many methods. There is given commonly used methods:

public int executeUpdate() is used to execute the update or delete query.

public List list() returns the result of the ralation as a list.

public Query setFirstResult(int rowno) specifies the row number from where record will be retrieved.

public Query setMaxResult(int rowno) specifies the no. of records to be retrieved from the relation
(table).

public Query setParameter(int position, Object value) it sets the value to the JDBC style query
parameter.
public Query setParameter(String name, Object value) it sets the value to a named query parameter.
Let’s take a look at CRUD operations using HQL.

FROM Clause

You will use FROM clause if you want to load a complete persistent objects into memory.
Following is the simple syntax of using FROM clause −

String hql = "FROM Employee";

Query query = session.createQuery(hql);

List results = query.list();

If you need to fully qualify a class name in HQL, just specify the package
and class name as follows −

String hql = "FROM com.hibernatebook.criteria.Employee";


Query query = session.createQuery(hql)
; List results = query.list();
Let’s take a look at CRUD operations using HQL.

AS Clause

The AS clause can be used to assign aliases to the classes in your HQL queries, especially when you
have the long queries. For instance, our previous simple example would be the following −

String hql = "FROM Employee AS E";

Query query = session.createQuery(hql);

List results = query.list();

The AS keyword is optional and you can also specify the alias directly after the class name, as follows −

String hql = "FROM Employee E";

Query query = session.createQuery(hql);

List results = query.list();


SELECT Clause
The SELECT clause provides more control over the result set then the from clause. If you want to obtain few
properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of
using SELECT clause to get just first_name field of the Employee object −

String hql = "SELECT E.firstName FROM Employee E";

Query query = session.createQuery(hql);

List results = query.list();

It is notable here that Employee.firstName is a property of Employee object rather than a field of the
EMPLOYEE table.

WHERE Clause

If you want to narrow the specific objects that are returned from storage, you use the WHERE clause. Following
is the simple syntax of using WHERE clause −
String hql = "FROM Employee E WHERE E.id = 10";

Query query = session.createQuery(hql);


Let’s take a look at CRUD operations using HQL.

Example of HQL to get all the records

//here persistent class name is Emp

Query query=session.createQuery("from Emp");

List list=query.list();
Hibernate parameter binding
There are two ways to parameter binding :

1. Named parameters binding

2. Positional parameters binding.

1. Named Parameters Binding:

This is the most common and user friendly way. It use colon followed by a
parameter name (:example) to define a named parameter.
Hibernate parameter binding

Example 1 – setParameter

The setParameter is smart enough to discover the parameter data type for you.

String hql = "from Student student where student.rollNumber= :rollNumber";

Query query = session.createQuery(hql);

query.setParameter("rollNumber", "3");

List result = query.list();


Hibernate parameter binding
2. Positional parameters

It’s use question mark (?) to define a named parameter, and you have to set your parameter according to
the position sequence. See example…

String hql = "from Student student where student.course= ? and student.studentName = ?";

Query query = session.createQuery(hql);

query.setString(0, "MCA");

query.setParameter(1, "Dinesh Rajput");

List result = query.list();

In Hibernate parameter binding, i would recommend always go for “Named parameters”, as it’s more easy
to maintain, and the compiled SQL statement can be reuse (if only bind parameters change) to increase
the performance.
Let’s take a look at CRUD operations using HQL.

Example of HQL update query

Transaction tx=session.beginTransaction();

Query q=session.createQuery("update User set name=:n where id=:i");

q.setParameter("n","Udit Kumar");

q.setParameter("i",111);

int status=q.executeUpdate();

System.out.println(status);

tx.commit();
Let’s take a look at CRUD operations using HQL.

Example of HQL delete query

Query query=session.createQuery("delete from Emp where id=100");

//specifying class name (Emp) not tablename

query.executeUpdate();
There are three way to pulling data from the database in the Hibernate.

1. Using session methods(get() and load() methods) -limited control to


accessing data

2. Using HQL – Slightly more control using where clause and other clauses
but there are some problems here… is more complicated to maintain in
case of bigger queries with lots of clauses.

3. Using Criteria API


GET() Load()

Get method of Hibernate session returns null if Load() method throws ObjectNotFoundExcception if
object is not found in cache as well as on database. objects is not found on cache as well as on database
but never returns null.

Get() involves database hit if object doesn’t exist in Load method can return proxy in place and only
session cache and returns a fully initialized object initialize the object or hit the database if my
which may involves several database cell. method other than getid() is called on persistent or
entity object. This lazy initialization increase the
performance.

Use if you are not sure that object exist in the Use if you are sure that object exist
database.
Criteria:

The hibernate criteria API is very Simplified API for fetching data from Criterion
objects.

The criteria API is an alternative of HQL (Hibernate Query Language) queries. It is


more powerful and flexible for writing tricky criteria functions and dynamic queries

Criteria criteria=session.createCriteria();
How to Use Hibernate Criteria

Object-Relational Mapping (ORM) provides many ways to retrieve data from


database.

Criteria is one of the efficient and easy way to query database.

Following is the simplest example of a criteria query is one, which will simply return

every object that corresponds to the Employee class.

Criteria cr = session.createCriteria(Employee.class);

List results = cr.list();


HCQL (Hibernate Criteria Query Language)

The Hibernate Criteria Query Language (HCQL) is used to fetch the records
based on the specific criteria.

The Criteria interface provides methods to apply criteria such as retrieving all the
records of table whose salary is greater than 50000 etc.

Advantage of HCQL

The HCQL provides methods to add criteria, so it is easy for the java
programmer to add criteria. The java programmer is able to add many criteria on
a query.
Criteria Interface

The Criteria interface provides many methods to specify criteria. The object of
Criteria can be obtained by calling the createCriteria() method of Session interface.

Criteria criteria=session.createCriteria();
Examples of Hibernate Criteria Query Language

There are given a lot of examples of HCQL.

Example of HCQL to get all the records

Crietria c=session.createCriteria(Emp.class);//passing Class class argument

List list=c.list();
Example of HCQL to get the 10th to 20th record

Crietria c=session.createCriteria(Emp.class);

c.setFirstResult(10);

c.setMaxResult(20);

List list=c.list();
The Restriction class in hibernate provide several methods that can be used as conditions (also
known as Criterion). These conditions are added to a criteria object with the add() method.
How to Use Hibernate Criteria

Restrictions with Criteria

You can use add() method available for Criteria object to add restriction for a criteria

query. Following is the example to add a restriction to return the records with salary is

equal to 2000 −

Criteria cr = session.createCriteria(Employee.class);

cr.add(Restrictions.gt("salary", 12000));

List results = cr.list();


Example of HCQL to get the records whose salary is greater than 12000

Crietria c=session.createCriteria(Emp.class);

c.add(Restrictions.gt("salary",12000));//salary is the propertyname

List list=c.list();
Order class

The Order class represents an order. The commonly used methods of Restrictions
class are as follows:

public static Order asc(String propertyName) applies the ascending order on the
basis of given property.

public static Order desc(String propertyName) applies the descending order on


the basis of given property.

Criteria cr = session.createCriteria(Employee.class);

cr.addOrder(Order.asc("emp_name"));
 Hibernate Criteria API provides Projection that we can use for aggregate functions
such as sum(), min(), max() etc.

 Hibernate Criteria API can be used with ProjectionList to fetch selected columns
only.
 Criteria in Hibernate can be used for join queries by joining multiple tables, useful
methods for Hibernate criteria join are createAlias(), setFetchMode() and
setProjection()

 Criteria in Hibernate API can be used for fetching results with conditions, useful
methods are add() where we can add Restrictions.

 Hibernate Criteria API provides addOrder() method that we can use for ordering
the results.
HCQL with Projection

We can fetch data of a particular column by projection such as name etc.

Let's see the simple example of projection that prints data of NAME column of the
table only.

Criteria c=session.createCriteria(Emp.class);

c.setProjection(Projections.property("name"));

List list=c.list();
Projections & Aggregations
The Criteria API provides the org.hibernate.criterion.Projections class, which can be used to get
average, maximum, or minimum of the property values. The Projections class is similar to the
Restrictions class, in t

Criteria cr = session.createCriteria(Employee.class); // To get total row count.

cr.setProjection(Projections.rowCount()); // To get average of a property.

cr. setProjection(Projections.avg("salary")); // To get distinct count of a property.

cr. setProjection(Projections.countDistinct("firstName")); // To get maximum of a property.

cr. setProjection(Projections.max("salary")); // To get minimum of a property

cr. setProjection(Projections.min("salary")); // To get sum of a property.

cr. setProjection(Projections.sum("salary"));
In Hibernate, either we create an object of an entity(pojo) and save it into the database, or
we fetch the data of an entity from the database.

Here, each entity is associated with the lifecycle. The entity object passes through the
different stages of the lifecycle.

The Hibernate lifecycle contains the following states: -

 Transient state ( StudentPojo obj = new studentPojo())

 Persistent state

 Detached state
x
Transient state

The transient state is the initial state of an object.

Once we create an instance of POJO class, then the object entered in the transient state.

Here, an object is not associated with the Session. So, the transient state is not related to any database.
Hence, modifications in the data don't affect any changes in the database.

The transient objects exist in the heap memory. They are independent of Hibernate.

Employee e=new Employee(); //Here, object enters in the transient state.

e.setId(101);

e.setFirstName("Gaurav");

e.setLastName("Chawla");
Persistent state

As soon as the object associated with the Session, it entered in the persistent state.

Hence, we can say that an object is in the persistence state when we save or persist it.

Here, each object represents the row of the database table.

So, modifications in the data make changes in the database.

We can use any of the following methods for the persistent state.

session.save(e);
session.persist(e);
session.update(e);
session.saveOrUpdate(e);
session.merge(e);
Detached State

Once we either close the session or clear its cache, then the object entered into the detached state.
As an object is no more associated with the Session, modifications in the data don't affect any
changes in the database.

However, the detached object still has a representation in the database.


If we want to persist the changes made to a detached object, it is required to reattach the application
to a valid Hibernate session.

To associate the detached object with the new hibernate session, use any of these methods -
load(), merge(), refresh(), update() or save() on a new session with the reference of the detached
object.

We can use any of the following methods for the detached state.

session.close();
session.clear();
session.detach(e);
session.evict(e);
Advantages of Hibernate Framework

Following are the advantages of hibernate framework:

1) Open Source and Lightweight


Hibernate framework is open source under the LGPL license and lightweight.

2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in
hibernate framework. There are two types of cache in hibernate framework first level
cache and second level cache. First level cache is enabled by default.

3) Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates


the database independent queries. So you don't need to write database specific
queries. Before Hibernate, if database is changed for the project, we need to change
the SQL query as well that leads to the maintenance problem.
Advantages of Hibernate Framework

4) Automatic Table Creation


Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually.

5) Simplifies Complex Join.

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

You might also like