Hibernate 3.X Material
Hibernate 3.X Material
What is Hibernate?
Hibernate is an implementation of the Java Persistence API (JPA) specification. And it is an open source
object/relational mapping frame work and makes developer life easy to connect and communicate with
different kind of relational databases in this universe.
1) Improved productivity
High-level object-oriented API
Less Java code to write
No SQL to write
ORM framework generates database-specific SQL for you
2) Improved performance :
Sophisticated caching
Eager loading
Lazy Loading
3) Improved maintainability :
A lot less code to write and It makes system more understandable and emphasizes more on business logic
rather than persistence work (SQLs)
4) Improved portability :
Switching to other SQL database requires few changes in Hibernate configuration file (Write once / run-
anywhere).
What is ORM?
ORM stands for Object Relational Mapping. And representing the relational data in the form of objects is
Called ORM
It allows a developer to map Plain Old Java Objects to relational database tables using (XML) configuration
files.
Hibernate High Level Architecture:
Hibernate Configuration:
We can configure Hibernate using configuration file hibernate.cfg.xml (or alternatively hibernate.properties ) and
mapping files *.hbm.xml And There are 2 ways to configure the Hibernate.
2) Programmatic configuration.
These two files are used to configure the Hibernate (connection driver class, connection URL, connection username,
connection password, dialect etc). If both files are present in the class path then hibernate.cfg.xml file overrides the
settings found in the hibernate.properties file.
hibernate.cfg.xml:
Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best
practice to store each object in an individual mapping file (i.e. mapping file per class) because storing large number of
persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the
same name as the persistent (POJO) class name. For example Account.class will have a mapping file named
Account.hbm.xml. Alternatively, hibernate annotations can be used as part of your persistent class code instead of the
*.hbm.xml files.
Employee.hbm.xml:
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API (JTA), and Java Naming and Directory
Interface (JNDI).
JDBC allows Hibernate to connect with Database execute the dynamic SQL that it generates. JNDI and JTA allow
Hibernate to be integrated with J2EE application servers.
Configuration Object:
We use Configuration Object for configuring the Hibernate. And it searches the hibernate.cfg.xml and hibernate
mapping file (Ex., Employee.hbm.xml) and reads the information available in 2 files and stores info in memory.
SessionFactory Object:
Configuration object is used to create a SessionFactory object which intern configures Hibernate for the application
using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread
safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You
would need one SessionFactory object per database using a separate configuration file. So if you are using multiple
databases then you would have to create multiple SessionFactory objects.
Session Object:
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be
instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through
a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and they should
be created and destroyed them as needed.
Transaction Object:
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality.
Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead managing
transactions in their own application code.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create
objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and
finally to execute the query.
private HibernateUtils() {
}
private static SessionFactory sessionFactoryObj = null;
private static String CONFIG_FILE_LOCATION
="sample/hibernate/config/hibernate.cfg.xml";
<property name="hbm2ddl.auto">update</property>
Hibernate code creates the tables that are mentioned in the hibernate mapping automatically.
NOTE: It is not at all recommended to call configure() and buildSessionFactory() methods repeatedly. This is why we
have to place them in Singleton design pattern like above HibernateUtils.
When openSession() gets executed, we will get the Session Object (It is equivalent to getting Connection). And it is not
an expensive operation.When we get the Session object, internally hibernate will create a cache object and it will be
associated with Session object. This is called First Level Cache (like Hashtable).
When session.save(employee) gets executed , the hibernate code registers the employee object in First Level Cache
with registration code.
When tx.commit() gets executed, The Hibernate code checks whether there are any registered objects in First Level
Cache or not .And it now checks to which class the pojo class object is created .After then, it finds to which Table this
pojo class is mapped.
Based on registration, hibernate code picks the appropriate query from JVM’s memory. Now it gets the data from pojo
class object and replaces all ‘?’ with the values. And now sends the query to the database.
<property name="show_sql">true</property>
we can use either load() or get() methods of Session Object to get a record
When session.load(employee, 1) gets executed, The hibernate code checks to which Table this pojo class is mapped
and gets appropriate Select Query from JVM’s memory like below
It replaces the “?” with 1 (2nd parameter of load method) and sends the query to Db.
The database will execute the query and send the resultset object to the hibernate. Now the hibernate will retrieve
the data from resultset object and place it inside the Employee pojo class object by calling setter methods. And now,
Employee pojo class object will be added to First Level Cache.
If the requested record is not available load() will return following exception.
When session.get(Employee.class, 1)gets executed, Whatever happens when load() gets executed,happens.
However, If the requested record is not available get() will return null
How to delete a record form Employee Table:
Approach 1: In this approach, we will load the record that we would like to delete from table and then we mark that
object as to be deleted. To mark the object as “to be deleted” we use delete(object).
When session.delete(employee)gets executed, The Employee Object is marked as to be deleted in the First Level
Cache.
When and tx.commit()gets executed, The Hibernate code checks whether there are any registered objects in First
Level Cache or not .And it now checks to which class the pojo class object is created .After then, it finds to which Table
this pojo class is mapped.
Based on registration, hibernate code picks the appropriate query from JVM’s memory. Now it gets the data from pojo
class object and replaces all ‘?’ with the values. And now sends the query to the database.
Approach 2: In this approach, we create the Employee pojo class object and pass the primary key value empID that
we would like to delete from the Employee table.And then we mark the Employee pojo class object as to be deleted
by using delete(employee).
Approach 1: In this approach, we will load the record that we would like to update in the table and then we change
that object with new value by calling appropriate setter method. Once If change the object , that object will be marked
as dirty object. If hibernate finds dirty objects , hibernate will issue the UPDATE query in the dirty object.
Approach 2: In this approach, we have to create Employee pojo and set the details which columns need to be
updated and then pass this Employee pojo to update() method.
evict (employee) method is used to remove any specified object from First Level Cache
merge (employee) method is used to add any specified object to First Level Cache
We can use these query API’s to communicate with any relational database by using Hibernate. The Hibernate uses
Pre-defined Dialect classes (Ex. MySQLDialect) to convert Query API into corresponding SQL API.
Hibernate Query Language (HQL) API
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the
table of the database. Instead of table name, we use class name in HQL. So it is database independent query
language.
Advantage of HQL
database independent
supports polymorphic queries
easy to learn for Java Programmer
Query Interface
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:
List list=query.list();
When query.list() gets executed , list() converts HQL into corresponding SQL query. Hibernate sends SQL query to
database. The database executes the SQL query and sends Resultset Object to Hibernate. By using this Resultset
object, Hibernate stores the data in the corresponding POJO Class Objects .And then Hibernate adds all these POJO
class objects to Arraylist object.
query.setFirstResult(5);
query.setMaxResult(10);
query.setParameter(0,10);
query.executeUpdate();
Similar to JDBC, In Hibernate HQL queries, we can have positional parameters.(Query with ’?’ Marks).In JDBC , the
positional parameter index starts with 1, whereas, in Hibernate, starts with 0.
Transaction tx=session.beginTransaction();
q.setParameter("name","Varma");
q.setParameter("empId",111);
int status=q.executeUpdate();
tx.commit();
Hibernate supports Named queries. In HQL, we pass the variable names instead of “?”.
Always the named queries variables start with”:” . The Named Queries does not improve performance, but only
readability of the code.
You may call avg(), min(), max() etc. aggregate functions by HQL. Let's see some common examples: