Overview of Hibernate - III
Overview of Hibernate - III
III
Objectives
In this session, you will learn to:
Identify Hibernate Query Language (HQL)
Implement criteria queries
Hibernate cache overview
Identifying HQL
Consider a scenario where you need to create an application that stores
students details in the SQL Server database. For this, you need to use
SQL queries to store the employee data in the database.
However, if you need to store the students details in Oracle database by
using the same application, you need to make changes in the queries as
per the Oracle database.
Therefore, if the database with which the application is communicating
changes, you need to make changes in the application code to access the
new database.
It is a time-consuming and error prone process.
To overcome this problem, Hibernate provides you with its own query
language, HQL, to communicate with the database.
Identifying HQL (Contd.)
HQL is an object-oriented query language that is similar to SQL, however
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.
Syntax and the clauses used in HQL are very similar to SQL. Therefore, a
developer who is aware of SQL can easily learn and use HQL.
Similar to SQL, HQL also supports various aggregation functions.
Various clauses used to summarize the data, such as GROUP BY and
ORDER BY, are supported in HQL.
Method Description
Query Query.setLong(String Is used to bind the long value (second parameter)
name, long val) with the long variable (first parameter) in a query
at run time.
Query Query.setFloat(String Is used to bind the float value (second parameter)
name, float val) with the float variable (first parameter) in a query
at run time.
Query Query.setDouble(String Is used to bind the double value (second
name, double val) parameter) with the double variable (first
parameter) in a query at run time.
Query Query.setDate(String name, Is used to bind the date value (second parameter)
Date date) with the date variable (first parameter) in a query
at run time.
Iterator iterate() Returns the query results as an Iterator object.
The SELECT clause provides more control over the result set than the
FROM clause.
The SELECT clause is used to get few properties of objects instead of
the complete object.
The following code illustrates how to use SELECT clause to get just
first_name field of the Student object:
The AS keyword is optional and you can also be use as shown in the
following code:
In the preceding code snippet, the query accepts the author name at run
time to query the database for object retrieval. var declares an
identifier that holds the value provided by the user at run time.
Hibernate provides the setXXX() methods, such as setString(),
setInteger(), and setDouble() available in the Query interface to
bind parameters of different data types to a query.
In the setXXX() method, xxx represents the data type of the
parameter that needs to be bound with the query.
Binding Parameters (Contd.)
To bind this identifier with the run-time value, you can use the
setString()method of the Query interface, as shown in the
following code snippet:
String authorname="Rosy";
query.setString("var", authorname);
SQLQuery query =
session.createSQLQuery("SELECT * FROM BOOKDETAILS");
query.addEntity(BookDetails.class);
List result=query.list();
for(Iterator itr=result.iterator();
itr.hasNext();)
{
BookDetails bkd=(BookDetails)itr.next();
..............
}
Criteria criteria =
session.createCriteria(Employee.class)
.add(Restrictions.gt("Emp_balance", 2000));
List myList = criteria.list();
The employee details are retrieved from a database table where employee
balance is greater than $2000.
Adding Restrictions (Contd.)
lt(String propertyName, Object value):
Accepts parameters similar to the gt()method.
Returns the result after comparing whether the value of a particular object
property is less than the specified value.
For example:
Criteria criteria =
session.createCriteria(Employee.class)
.add(Restrictions.lt("Emp_balance", 2000));
List myList = criteria.list();
The employee details are retrieved from a database table where employee
balance is less than $2000.
Adding Restrictions (Contd.)
like(String propertyName, Object value):
Accepts a property of an object as the first parameter and string pattern
that needs to be matched with the value of that property as the second
parameter.
Returns the result after comparing the object property with the specified
pattern.
For example:
Criteria criteria =
session.createCriteria(Customer.class)
.add(Restrictions.like("cust_name", "%J%"))
List myList = criteria.list();
The customer details are retrieved from a database table where customer
name contains character J in their name.
Adding Restrictions (Contd.)
between(String propertyName,Object low,Object
high):
Accepts a property of an object as the first parameter. The second and third
parameters specify a range by providing the minimum and maximum values,
respectively.
Compares the value of the specified property with the minimum and
maximum values.
Returns those results where the property value is between these minimum
and maximum values.
For example:
Criteria criteria =
session.createCriteria(Employee.class
)
.add(Restrictions.between("Emp_balance",
new Integer(3000), new Integer(5000)));
List myList = criteria.list();
The employee details are retrieved from a database table where employee
balance is between $3000 and $5000.
Pagination Using Criteria
The following two methods of the Criteria interface are used for
pagination:
Method Description
public Criteria This method takes an integer that
setFirstResult(int
firstResult)
represents the first row in your result
set, starting with row 0.
public Criteria This method tells Hibernate to retrieve a
setMaxResults(int
maxResults)
fixed number maxResults of objects.
The following code illustrates how you can extend to fetch 10 rows at a
time:
Criteria cr =
session.createCriteria(Employee.class);
cr.setFirstResult(1);
cr.setMaxResults(10);
List results =
cr.list();
Sorting the Results Using Criteria
The Criteria API provides the org.hibernate.criterion.Order
class to sort your result set in either ascending or descending order,
according to one of your object's properties.
The following example illustrates how you would use the Order class to
sort the result set:
Criteria cr =
session.createCriteria(Employee.class)
;
cr.add(Restrictions.gt("salary",
2000));
crit.addOrder(Order.desc("salary"));
List results = cr.list();
Identifying the Object States
The following figure depicts the object states.
Develop an application
Employee Page
EmpID:
In a Web EmpName:
application, to EmpDesig:
collect EmpAddress:
employee Employee
Submit
details object
Database
The Transient State (Contd.)
Persistent
Transient transformed object
saved Database
object
table
Database identity
associated
Example:
Employee
information
store Database
The Persistent State (Contd.)
store Implement
different
Database operations
retrieve Delete
object
Update
Persist Retrieve data
object data
Working with Persistent Objects (Contd.)
Persisting Objects:
To store application data into the database tables, you need to persist the
application objects.
For example, to store employee information in the database, you need to
persist objects that contains employee information in the database.
Hibernate provides the save()method to persist an object into a database
table.
The following code illustrate how to persist object:
..............
transaction.begin();
Employee
empUpdate=(Employee)session.load(Employee.class,
objID);
empUpdate.setAddress("Hudson Street,
California");
session.update(empUpdate);
transaction.commit();
Working with Persistent Objects (Contd.)
Deleting Objects:
You can delete an already persistent object by using the delete()or the
remove()method. The process of deleting an object is similar to the
process of modifying a persistent object.
The following code illustrate how to delete object:
transaction.begin();
Employee
empUpdate=(Employee)session.load(Employee.class,
objID);
session.delete(empUpdate);
transaction.commit();
Identify Hibernate Cache
Caching is used for application performance optimization.
It resides between the application and the database to avoid the number
of database hits as many as possible to give a better performance for
performance critical applications.
Hibernate utilizes a multilevel caching schemes, which are:
Identify Hibernate Cache (Contd.)
First-level cache:
The first-level cache is the session cache and is a mandatory cache through
which all requests must pass. The Session object keeps an object under its
own power before committing it to the database.
If multiple updates are issued to an object, Hibernate tries to delay doing
the update as long as possible to reduce the number of update SQL
statements issued.
If the session is closed, all the objects being cached are lost and either
persisted or updated in the database.
Identify Hibernate Cache (Contd.)
Second-level cache:
Second-level cache is an optional cache and first-level cache will always be
consulted before any attempt is made to locate an object in the
second-level cache.
The second-level cache can be configured on a per-class and per-collection
basis and mainly responsible for caching objects across sessions.
Any third-party cache can be used with Hibernate.
An org.hibernate.cache.CacheProvider interface is provided, which
must be implemented to provide Hibernate with a handle to the cache
implementation.
Identify Hibernate Cache (Contd.)
Query-level cache:
Hibernate implements a cache for query result sets that integrates closely
with the second-level cache.
It is an optional feature and requires two additional physical cache regions
that hold the cached query results and the timestamps when a table was
last updated.
This is only useful for queries that are run frequently with the same
parameters.
Identify Hibernate Cache (Contd.)
Concurrency strategies:
A concurrency strategy is a mediator which responsible for storing items of
data in the cache and retrieving them from the cache. If you are going to
enable a second-level cache, you will have to decide, for each persistent
class and collection, the following cache concurrency strategy to need to
choose.
Transactional: Use this strategy for read-mostly data where it is critical to
prevent stale data in concurrent transactions, in the rare case of an update.
Read-write: Again use this strategy for read-mostly data where it is critical to
prevent stale data in concurrent transactions, in the rare case of an update.
Nonstrict-read-write: This strategy makes no guarantee of consistency between
the cache and the database. Use this strategy if data hardly ever changes and a
small likelihood of stale data is not of critical concern.
Read-only: A concurrency strategy suitable for data which never changes. Use it
for reference data only.
Identify Cache provider
Hibernate allows you to choose a single cache provider for the whole
application, which are:
Cache Name Description
EHCache It can cache in memory or on disk and clustered caching and it supports
the optional Hibernate query result cache.
OSCache Supports caching to memory and disk in a single JVM, with a rich set of
expiration policies and query cache support.
JBoss Cache A fully transactional replicated clustered cache also based on the JGroups
multicast library. It supports replication or invalidation, synchronous or
asynchronous communication, and optimistic and pessimistic locking.
The Hibernate query cache is supported
Summary
HQL is an object-oriented query language that is similar to SQL, however
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.
In a Hibernate application, you can create and execute HQL queries with
the help of the org.hibernate.
Query interface and its methods. The Query interface provides various
methods to create and execute queries.
FROM clause is used to load a complete persistent objects into memory.
The SELECT clause provides more control over the result set than the
from clause.
AS clause is used to assign aliases to the classes in your HQL queries,
specially when you have long queries.
Summary (Contd.)
WHERE clause is used to narrow the specific objects that are returned
from storage.
ORDER BY clause is used to sort the HQL query results.
GROUP BY clause lets Hibernate pull information from the database and
group it based on a value of an attribute and use the result to include an
aggregate value.
The following two types of parameter binding is supported by HQL:
Named parameters
Positional parameters