Hibernate Notes
Hibernate Notes
Hibernate Notes
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;
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
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
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 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)
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.
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
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 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 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 −
If you need to fully qualify a class name in HQL, just specify the package
and class name as follows −
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 −
The AS keyword is optional and you can also specify the alias directly after the class name, as follows −
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";
List list=query.list();
Hibernate parameter binding
There are two ways to parameter 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.
query.setParameter("rollNumber", "3");
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.setString(0, "MCA");
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.
Transaction tx=session.beginTransaction();
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.
query.executeUpdate();
There are three way to pulling data from the database in the Hibernate.
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.
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.
Criteria criteria=session.createCriteria();
How to Use Hibernate Criteria
Following is the simplest example of a criteria query is one, which will simply return
Criteria cr = session.createCriteria(Employee.class);
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
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
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));
Crietria c=session.createCriteria(Emp.class);
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.
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
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
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.
Persistent state
Detached state
x
Transient state
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.
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.
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.
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
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.