0% found this document useful (0 votes)
50 views56 pages

Overview of Hibernate - III

Hibernate provides an object-relational mapping tool called Hibernate Query Language (HQL) that allows developers to write queries using objects instead of tables and columns. This document discusses HQL, including identifying HQL, creating and executing queries using the Query interface, commonly used clauses like FROM, WHERE, ORDER BY, and binding parameters to queries. It explains how HQL queries are translated to SQL and executed on the database, and how developers can avoid hardcoding values by binding parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views56 pages

Overview of Hibernate - III

Hibernate provides an object-relational mapping tool called Hibernate Query Language (HQL) that allows developers to write queries using objects instead of tables and columns. This document discusses HQL, including identifying HQL, creating and executing queries using the Query interface, commonly used clauses like FROM, WHERE, ORDER BY, and binding parameters to queries. It explains how HQL queries are translated to SQL and executed on the database, and how developers can avoid hardcoding values by binding parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Overview of Hibernate -

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.

To store and retrieve data from a database, you need to:


Create and execute queries.
Bind parameters, if any.
Iterate through the result set.
Creating and Executing Queries
In a Hibernate application, you can create and execute HQL queries with
the help of the org.hibernate.
The Query interface provides various methods to create and execute
queries.
The following table lists the commonly used methods of the Query
interface.
Method Description
Query Is used to create a query in the current session by
Session.createQuery(String using the specified query string passed as a
queryString)
parameter.
Query Is used to add the specified comment, passed as a
Query.setComment(String parameter, to the query that invokes this method.
comment)
Query Query.setString(String Is used to bind the string value (second
name, String val) parameter) with the variable (first parameter) in a
query at run time.

Query Is used to bind the integer value (second


Query.setInteger(String parameter) with the integer variable (first
name, int val)
parameter) in a query at run time.
Creating and Executing Queries (Contd.)

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.

List list() Returns the query results as a List object.


Query Sets a cursor in the query to retrieve rows starting
setFirstResult(int from the specified index. By default, the index
firstResult)
starts from 0.
Creating and Executing Queries (Contd.)
Consider a scenario where you have created the EmpDetails class in
your application to store information about different employees in a
database table, EMPDETAILS. The EmpDetails class is mapped with
the EMPDETAILS table in the database by using the Hibernate mapping
file.
You can retrieve employees information from a database using an HQL
query, as shown in the following code snippet:

Query query = session.createQuery("FROM EmpDetails");


Creating and Executing Queries (Contd.)
The commonly used clauses in HQL queries are:
FROM
SELECT
AS
WHERE
ORDER BY
GROUP BY
Creating and Executing Queries (Contd.)
FROM clause is used to load a complete persistent objects into memory.
The following code illustrate the FROM clause:

String hql = "FROM Employee";


Query query = session.createQuery(hql);
List results = query.list();

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:

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


Query query = session.createQuery(hql);
List results = query.list();
Creating and Executing Queries (Contd.)
AS clause is used to assign aliases to the classes in your HQL queries,
specially when you have long queries.
The following code illustrate the As clause:

String hql = "FROM Employee AS E";


Query query = session.createQuery(hql);
List results = query.list();

The AS keyword is optional and you can also be use as shown in the
following code:

String hql = "FROM Employee E";


Query query = session.createQuery(hql);
List results = query.list();
Creating and Executing Queries (Contd.)
WHERE clause is used to narrow the specific objects that are returned
from storage.
The following code illustrate the WHERE clause:

String hql = "FROM Employee E WHERE E.id = 10";


Query query = session.createQuery(hql);
List results = query.list();

ORDER BY clause is used to sort the HQL query results.


You can order the results by any property on the objects in the result set
either ascending (ASC) or descending (DESC).
The following code illustrate the ORDER BY clause:

String hql = "FROM Employee E WHERE E.id > 10


ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();
Creating and Executing Queries (Contd.)
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 code illustrate the GROUP BY clause:

String hql = "SELECT SUM(E.salary), E.firtName


FROM Employee E " + "GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();
Creating and Executing Queries (Contd.)
Aggregate methods:
HQL supports various aggregate methods, similar to SQL.
The following table contains aggregate methods, which work the same way
in HQL as in SQL:
Functions Description
avg(property name) The average of a property's value

count(property name or *) The number of times a property occurs in the results


max(property name) The maximum value of the property values
min(property name) The minimum value of the property values
sum(property name) The sum total of the property values

The following code illustrate the use of the count method:


String hql =
"SELECT count(distinct E.firstName) FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();
Binding Parameters
Consider a scenario where you need to retrieve information from the
database based on conditions. However, you are not aware of the value
that needs to be specified as a condition in the HQL query.
For example, you want that a user should be able to specify the name of
an author at run time to retrieve information about the books written by
that author. For this, you need to create an HQL query and bind the
name of the author as a parameter to it during run time.
Without parameter binding, you have to concatenate the parameter
String as displayed in the following code:

String hql = "from Employee e where e.ID = '" + ID + "'";


List result = session.createQuery(hql).list();

The following two types of parameter binding is supported by HQL:


Named parameters
Positional parameters
Binding Parameters (Contd.)
Named parameter: is the most common way that use colon followed by
a parameter name (:example) to define a named parameter.
For example, consider the following code snippet:

Query query = session.createQuery("FROM


Test.BookDetails WHERE author=:var");

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);

Positional parameters: use question mark (?) to define a named


parameter, and need to set parameter according to the position
sequence.

String hql = "from Employee e where e.ID = ?


and e.Name = ?";
List result = session.createQuery(hql)
.setString(0, "7277")
.setParameter(1, "Peter")
.list();
Iterating Through the Result Set
To retrieve data from a database table, the query returns a result set
containing one or more rows stored in the table.
You can use the list() and iterate() methods of the Query
interface to iterate through the result set returned from a query.
The following code snippet illustrate how to iterate data from the
BOOKDETAILS table through the result set:

Query query = session.createQuery("FROM Test.BookDetails");


for(Iterator itr=query.iterate();itr.hasNext();)
{
BookDetails bkd=(BookDetails)itr.next();
System.out.println(bkd.getBookID());
}
Pagination Using Query
Pagination for a Web application is used when an application returned a
large set of data for a query.
The Web application would page through the database query result set
to build the appropriate page for the user.
The following two methods of the Query interface are used for
pagination:
Method Description
Query This method takes an integer that
setFirstResult(int
startPosition)
represents the first row in your result
set, starting with row 0.
Query This method tells Hibernate to retrieve a
setMaxResults(int
maxResult)
fixed number maxResults of objects.
Pagination Using Query (Contd.)
The following code illustrates how you can extend to fetch 10 rows at a
time:

String hql = "FROM Employee";


Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list();
Using Native SQL
While migrating from an SQL/JDBC-based application to Hibernate, you
can retain the SQL queries already written in the application by using
native SQL queries.
Hibernate provides the org.hibernate.SQLQuery interface to use
native SQL queries in your application.
This interface implements the Query interface and provides methods to
create and use native SQL queries in a Hibernate application.
The following table lists the commonly used methods of the SQLQuery
interface to create and use native SQL queries.
Method Description
SQLQuery Is used to create a native SQL query by
Session.createSQLQuery(Strin using the string passed as a parameter.
g queryString)
SQLQuery Is used to declare the type of entity that
SQLQuery.addEntity(Class is associated with the table from where
entityType)
the current native SQL query retrieves
the data. This method accepts the class
name as its parameter.
Using Native SQL (Contd.)
The following code snippet illustrate how to use native SQL in hibernate
application:

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();
..............
}

The createSQLQuery()method is used to create a native SQL query


that retrieves all the records from the BOOKDETAILS table.
The addEntity()method specifies that the BookDetails class is an
entity type associated with the BOOKDETAILS table.
The list()method of the Query interface is used to retrieve the result
from the query in a List reference, result.
Working with HQL Joins
Joins are used to select the data from multiple tables of the database,
when there exist relationship.
With joins, its possible to select data from multiple tables of the
database by construction a single query.
Hibernate supports following types of joins.
Left Join: the objects from both sides of the join are selected and more
objects from left side are selected, even though no equal objects are there
at right side.
Right Join: equal objects are selected from database and more objects are
from right side of join are selected even though there is no equal objects
are exist left side.
Full Join: both equal and un-equal objects from both sides of join are
selected.
Inner Join: both equal and un-equal objects from both sides of join are
selected.
Working with HQL Joins (Contd.)
At the time of construction the join statements, we need to use the
properties created in POJO class to apply relationship between the
objects.
The DEFAULT join in hibernate is Inner join.
To construct a join statement, we use either HQL, or NativeSql.
The following code illustrates how to use left outer join in HQL:

Session session = factory.openSession();


Query qry= session.createQuery("select v.vendorName,
c.customerName from Vendor v Left Join v.children c");
List l = qry.list();
Iterator it=l.iterator();
while(it.hasNext())
{
Object rows[] = (Object[])it.next();
System.out.println(rows[0]+ " -- " +rows[1]);
}
Implementing Criteria Queries
HQL offers a rich functionality of querying databases using objects and
their properties.
To write an HQL query, the users need to have prior knowledge of SQL.
As a result, creating complex HQL queries based on multiple criteria is
difficult.
Since the HQL queries are parsed and executed at run time, it is difficult
to rectify the errors that occur during application execution.
Hibernate solves this problem by supporting the use of criteria queries in
an application.
The criteria queries:
Are pure object-oriented queries written as Java code.
Can be created without using the SQL syntax or the SQL clauses.
Are parsed at compile time. Therefore, if an error occurs in the query, it is
easy for the developer to identify and rectify it.
Building a Criteria Query
The org.hibernate.Criteria interface
Is used to create criteria queries
contains methods required to create and use the criteria queries
The following table lists the commonly used methods of the Criteria
interface.
Method Description
Criteria Is used to create a criteria query for the given
createCriteria(Class entity class.
persistenceClass)
List list() Is used to retrieve the result from a criteria
query in a reference of the List collection.
Criteria add(Criterion Is used to add a condition in a criteria query by
criterion) specifying the condition as a parameter. The
condition for a criteria query is specified as an
object of the Criterion interface.
Building a Criteria Query (Contd.)
The following code snippet illustrates the use of the Criteria interface:

Criteria criteria = session.createCriteria


(Customer.class)
List myList = criteria.list();

The createCriteria()method accepts the class name as its argument


and returns an object of the Criteria interface.
The criteria query retrieves all the details from the database table
associated with the Customer class.
The list()method of the Criteria interface is used to retrieve the list
of objects fetched from the database.
Adding Restrictions
To use the condition-based criteria queries in a Hibernate application,
you need to add restrictions to the criteria query.
Hibernate provides the org.hibernate.criterion.Restrictions
class to add a restriction in a criteria query.
You can create a criteria query with a restriction by using the add()
method of the Criteria interface.
The following code illustrate how to add restriction:
Criteria criteria =
session.createCriteria(Customer.class)
criteria.add(Restrictions.eq("cust_city", "Dallas"));
List myList = criteria.list();

The add()method of the Criteria interface accepts an instance of the


Criterion interface.
The instance of the Criterion interface is created by invoking the eq()
method of the Restrictions class. This method accepts two
parameters.
Adding Restrictions (Contd.)
You can also create restrictions based on other criterion.
For this, the Restrictions class provides the following static methods
in addition to the eq()method:
gt(String propertyName, Object value)
lt(String propertyName, Object value)
ge(String propertyName, Object value)
le(String propertyName, Object value)

like(String propertyName, Object value)


between(String propertyName, Object low, Object
high)
Adding Restrictions (Contd.)
gt(String propertyName, Object value):
Accepts a property of an object as the first parameter and a value that
needs to be compared with the value of that property as the second
parameter.
Returns the result after comparing whether the value of a particular object
property is greater than the specified value.
For example:

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

Create classes to work with the user inputs

Create an object of a class and initialize it to receive the


user inputs

Perform different operations on the objects to process the


user data

Store the result in the database or display it to the user

Discard and garbage collect the object


Identifying the Object States (Contd.)
An object passes through various states creation until it is stored in a
database.

The Life Cycle of an Object


The Transient State

Employee Page

EmpID:
In a Web EmpName:
application, to EmpDesig:
collect EmpAddress:
employee Employee
Submit
details object

Database
The Transient State (Contd.)

Object created by using the new operator is said to be in


the transient state.

Object in the transient state is not associated with


any database table row.

Object loses its state if it is not referred by any


object.

A transient object becomes inaccessible for other objects


and is available for garbage collection if it losses its state.
The Persistent State

Persistent
Transient transformed object
saved Database
object
table

Database identity
associated

Example:

Map the Employee class


with a database table in
the Hibernate mapping file

Employee
information
store Database
The Persistent State (Contd.)

Hibernate manages the objects that are being


persisted or retrieved from the database in the
persistence context.

Persistence context is a logical cache where the


objects are manipulated before they are
permanently stored in the database.
The Detached State
The object is transformed into the detached state, after storing the data
in the database and the session that was being used to store objects in
the database is closed.
The close(), clear(), or evict() methods available in the
org.hibernate.Session interface are used to transform the object to
detached state.
Working with Persistent Objects
In an application that performs the storage and retrieval of data from the
database, you need to implement different operations on the objects
that hold the user data.
For example, to store the user data into a database table, you need to
persist the object that holds the user data into the database.
The following figure depicts the actions that can be perform on objects:

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:

Employee emp = new Employee();


emp.setEmpID(...);
emp.setEmpName( ... );
...............
...............
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Serializable objId = session.save(emp);
tx.commit();
Working with Persistent Objects (Contd.)
Retrieving Objects:
To perform an operation on a persistent object, you need to retrieve that
object in the persistence context.
For this, you can use the load()or the get()method.
Both the load() and the get()method accepts two parameters. The first
parameter accepts the class name of the object being accessed from the
database. The second parameter accepts a Serializable reference, which is
an identifier for the object to be retrieved.
following code illustrate how to retrieve object:

Transaction transaction = session.beginTransaction();


Employee emp=new
Employee();
emp.setEmpId(109);
emp.setName("Martin");
emp.setAddress("Silver Street,
California"); Serializable
objID=session.save(emp);
transaction.commit(); objID);
transaction.begin();
Employee
empUpdate=(Employee)session.load(Employee.class,
empUpdate.setAddress("Hudson Street, California");
..............
transaction.commit();
Working with Persistent Objects (Contd.)
Updating Objects:
To update the already persistent objects, you need to first load the objects
in the persistence context by using the get()or the load()method.
To update the modified object into the database table, you can use the
update()or the saveOrUpdate()method.

The following code illustrate how to update 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.

warmCache A cluster cache based on JGroups. It uses clustered invalidation but


doesn't support the Hibernate query cache

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

Pagination for a Web application is used when an application returned a


large set of data for a query.
Hibernate provides the org.hibernate.SQLQuery interface to use
native SQL queries in your application.
Joins are used to select the data from multiple tables of the database,
when there exist relationship.
Summary (Contd.)
The criteria queries:
Are pure object-oriented queries written as Java code.
Can be created without using the SQL syntax or the SQL clauses.
Hibernate provides the org.hibernate.criterion.Restrictions
class to add a restriction in a criteria query.
Object created by using the new operator is said to be in the transient
state.
Hibernate manages the objects that are being persisted or retrieved
from the database in the persistence context
The object is transformed into the detached state, after storing the data
in the database and the session that was being used to store objects in
the database is closed.
Caching is used for application performance optimization.
Summary (Contd.)
The first-level cache is the session cache and is a mandatory cache
through which all requests must pass.
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.
Query-level cache is only useful for queries that are run frequently with
the same parameters.

You might also like