SlideShare a Scribd company logo
© People Strategists www.peoplestrategists.com Slide 1 of 56
Overview of Hibernate -III
© People Strategists www.peoplestrategists.com Slide 2 of 56
In this session, you will learn to:
Identify Hibernate Query Language (HQL)
Implement criteria queries
Hibernate cache overview
Objectives
© People Strategists www.peoplestrategists.com Slide 3 of 56
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
© People Strategists www.peoplestrategists.com Slide 4 of 56
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.
Identifying HQL (Contd.)
© People Strategists www.peoplestrategists.com Slide 5 of 56
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.
Creating and Executing Queries
Method Description
Query Session.createQuery(String
queryString)
Is used to create a query in the current session by
using the specified query string passed as a
parameter.
Query Query.setComment(String
comment)
Is used to add the specified comment, passed as a
parameter, to the query that invokes this method.
Query Query.setString(String name,
String val)
Is used to bind the string value (second
parameter) with the variable (first parameter) in a
query at run time.
Query Query.setInteger(String
name, int val)
Is used to bind the integer value (second
parameter) with the integer variable (first
parameter) in a query at run time.
© People Strategists www.peoplestrategists.com Slide 6 of 56
Creating and Executing Queries (Contd.)
Method Description
Query Query.setLong(String name,
long val)
Is used to bind the long value (second parameter)
with the long variable (first parameter) in a query
at run time.
Query Query.setFloat(String name,
float val)
Is used to bind the float value (second parameter)
with the float variable (first parameter) in a query
at run time.
Query Query.setDouble(String name,
double val)
Is used to bind the double value (second
parameter) with the double variable (first
parameter) in a query at run time.
Query Query.setDate(String name,
Date date)
Is used to bind the date value (second parameter)
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 setFirstResult(int
firstResult)
Sets a cursor in the query to retrieve rows starting
from the specified index. By default, the index
starts from 0.
© People Strategists www.peoplestrategists.com Slide 7 of 56
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:
Creating and Executing Queries (Contd.)
Query query = session.createQuery("FROM EmpDetails");
© People Strategists www.peoplestrategists.com Slide 8 of 56
The commonly used clauses in HQL queries are:
FROM
SELECT
AS
WHERE
ORDER BY
GROUP BY
Creating and Executing Queries (Contd.)
© People Strategists www.peoplestrategists.com Slide 9 of 56
FROM clause is used to load a complete persistent objects into memory.
The following code illustrate the FROM clause:
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:
Creating and Executing Queries (Contd.)
String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();
String hql = "SELECT E.firstName FROM STUDENT";
Query query = session.createQuery(hql);
List results = query.list();
© People Strategists www.peoplestrategists.com Slide 10 of 56
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:
The AS keyword is optional and you can also be use as shown in the
following code:
Creating and Executing Queries (Contd.)
String hql = "FROM Employee AS E";
Query query = session.createQuery(hql);
List results = query.list();
String hql = "FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();
© People Strategists www.peoplestrategists.com Slide 11 of 56
WHERE clause is used to narrow the specific objects that are returned
from storage.
The following code illustrate the WHERE clause:
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:
Creating and Executing Queries (Contd.)
String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();
String hql = "FROM Employee E WHERE E.id > 10
ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();
© People Strategists www.peoplestrategists.com Slide 12 of 56
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:
Creating and Executing Queries (Contd.)
String hql = "SELECT SUM(E.salary), E.firtName
FROM Employee E " + "GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();
© People Strategists www.peoplestrategists.com Slide 13 of 56
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:
The following code illustrate the use of the count method:
Creating and Executing Queries (Contd.)
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
String hql =
"SELECT count(distinct E.firstName) FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();
© People Strategists www.peoplestrategists.com Slide 14 of 56
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:
The following two types of parameter binding is supported by HQL:
Named parameters
Positional parameters
Binding Parameters
String hql = "from Employee e where e.ID = '" + ID + "'";
List result = session.createQuery(hql).list();
© People Strategists www.peoplestrategists.com Slide 15 of 56
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:
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.)
Query query = session.createQuery("FROM
Test.BookDetails WHERE author=:var");
© People Strategists www.peoplestrategists.com Slide 16 of 56
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:
Positional parameters: use question mark (?) to define a named
parameter, and need to set parameter according to the position
sequence.
Binding Parameters (Contd.)
String authorname="Rosy";
query.setString("var", authorname);
String hql = "from Employee e where e.ID = ?
and e.Name = ?";
List result = session.createQuery(hql)
.setString(0, "7277")
.setParameter(1, "Peter")
.list();
© People Strategists www.peoplestrategists.com Slide 17 of 56
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:
Iterating 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());
}
© People Strategists www.peoplestrategists.com Slide 18 of 56
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:
Pagination Using Query
Method Description
Query
setFirstResult(int
startPosition)
This method takes an integer that
represents the first row in your result
set, starting with row 0.
Query
setMaxResults(int
maxResult)
This method tells Hibernate to retrieve a
fixed number maxResults of objects.
© People Strategists www.peoplestrategists.com Slide 19 of 56
The following code illustrates how you can extend to fetch 10 rows at a
time:
Pagination Using Query (Contd.)
String hql = "FROM Employee";
Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list();
© People Strategists www.peoplestrategists.com Slide 20 of 56
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.
Using Native SQL
Method Description
SQLQuery
Session.createSQLQuery(String
queryString)
Is used to create a native SQL query by
using the string passed as a parameter.
SQLQuery SQLQuery.addEntity(Class
entityType)
Is used to declare the type of entity that
is associated with the table from where
the current native SQL query retrieves
the data. This method accepts the class
name as its parameter.
© People Strategists www.peoplestrategists.com Slide 21 of 56
The following code snippet illustrate how to use native SQL in hibernate
application:
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.
Using Native SQL (Contd.)
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();
..............
}
© People Strategists www.peoplestrategists.com Slide 22 of 56
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
© People Strategists www.peoplestrategists.com Slide 23 of 56
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:
Working with HQL Joins (Contd.)
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]);
}
© People Strategists www.peoplestrategists.com Slide 24 of 56
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.
Implementing Criteria Queries
© People Strategists www.peoplestrategists.com Slide 25 of 56
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.
Building a Criteria Query
Method Description
Criteria
createCriteria(Class
persistenceClass)
Is used to create a criteria query for the given
entity class.
List list() Is used to retrieve the result from a criteria
query in a reference of the List collection.
Criteria add(Criterion
criterion)
Is used to add a condition in a criteria query by
specifying the condition as a parameter. The
condition for a criteria query is specified as an
object of the Criterion interface.
© People Strategists www.peoplestrategists.com Slide 26 of 56
The following code snippet illustrates the use of the Criteria interface:
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.
Criteria criteria = session.createCriteria
(Customer.class)
List myList = criteria.list();
Building a Criteria Query (Contd.)
© People Strategists www.peoplestrategists.com Slide 27 of 56
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:
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
Criteria criteria =
session.createCriteria(Customer.class)
criteria.add(Restrictions.eq("cust_city", "Dallas"));
List myList = criteria.list();
© People Strategists www.peoplestrategists.com Slide 28 of 56
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.)
© People Strategists www.peoplestrategists.com Slide 29 of 56
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:
The employee details are retrieved from a database table where employee
balance is greater than $2000.
Adding Restrictions (Contd.)
Criteria criteria =
session.createCriteria(Employee.class)
.add(Restrictions.gt("Emp_balance", 2000));
List myList = criteria.list();
© People Strategists www.peoplestrategists.com Slide 30 of 56
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:
The employee details are retrieved from a database table where employee
balance is less than $2000.
Adding Restrictions (Contd.)
Criteria criteria =
session.createCriteria(Employee.class)
.add(Restrictions.lt("Emp_balance", 2000));
List myList = criteria.list();
© People Strategists www.peoplestrategists.com Slide 31 of 56
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:
The customer details are retrieved from a database table where customer
name contains character J in their name.
Adding Restrictions (Contd.)
Criteria criteria =
session.createCriteria(Customer.class)
.add(Restrictions.like("cust_name", "%J%"))
List myList = criteria.list();
© People Strategists www.peoplestrategists.com Slide 32 of 56
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:
The employee details are retrieved from a database table where employee
balance is between $3000 and $5000.
Adding Restrictions (Contd.)
Criteria criteria =
session.createCriteria(Employee.class)
.add(Restrictions.between("Emp_balance", new
Integer(3000), new Integer(5000)));
List myList = criteria.list();
© People Strategists www.peoplestrategists.com Slide 33 of 56
The following two methods of the Criteria interface are used for
pagination:
The following code illustrates how you can extend to fetch 10 rows at a
time:
Pagination Using Criteria
Method Description
public Criteria
setFirstResult(int
firstResult)
This method takes an integer that
represents the first row in your result
set, starting with row 0.
public Criteria
setMaxResults(int
maxResults)
This method tells Hibernate to retrieve a
fixed number maxResults of objects.
Criteria cr =
session.createCriteria(Employee.class);
cr.setFirstResult(1);
cr.setMaxResults(10);
List results = cr.list();
© People Strategists www.peoplestrategists.com Slide 34 of 56
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:
Sorting the Results Using Criteria
Criteria cr =
session.createCriteria(Employee.class);
cr.add(Restrictions.gt("salary", 2000));
crit.addOrder(Order.desc("salary"));
List results = cr.list();
© People Strategists www.peoplestrategists.com Slide 35 of 56
The following figure depicts the object states.
Identifying 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
© People Strategists www.peoplestrategists.com Slide 36 of 56
An object passes through various states creation until it is stored in a
database.
Identifying the Object States (Contd.)
The Life Cycle of an Object
© People Strategists www.peoplestrategists.com Slide 37 of 56
The Transient State
In a Web
application, to
collect
employee
details
Employee Page
EmpID:
EmpName:
EmpDesig:
EmpAddress:
Submit
Employee
object
Database
© People Strategists www.peoplestrategists.com Slide 38 of 56
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.
© People Strategists www.peoplestrategists.com Slide 39 of 56
The Persistent State
Transient
object
saved Database
table
transformed
Persistent
object
Database identity
associated
Example:
Employee
information
Databasestore
Map the Employee class
with a database table in
the Hibernate mapping file
© People Strategists www.peoplestrategists.com Slide 40 of 56
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 Persistent State (Contd.)
© People Strategists www.peoplestrategists.com Slide 41 of 56
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.
The Detached State
© People Strategists www.peoplestrategists.com Slide 42 of 56
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:
Working with Persistent Objects
Database
retrieve
store Implement
different
operations
Persist
object
Retrieve
data
Update
data
Delete
object
© People Strategists www.peoplestrategists.com Slide 43 of 56
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:
Working with Persistent Objects (Contd.)
Employee emp = new Employee();
emp.setEmpID(...);
emp.setEmpName( ... );
...............
...............
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
Serializable objId = session.save(emp);
tx.commit();
© People Strategists www.peoplestrategists.com Slide 44 of 56
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:
Working with Persistent Objects (Contd.)
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();
transaction.begin();
Employee empUpdate=(Employee)session.load(Employee.class, objID);
empUpdate.setAddress("Hudson Street, California");
..............
transaction.commit();
© People Strategists www.peoplestrategists.com Slide 45 of 56
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:
Working with Persistent Objects (Contd.)
..............
transaction.begin();
Employee
empUpdate=(Employee)session.load(Employee.class,
objID);
empUpdate.setAddress("Hudson Street,
California");
session.update(empUpdate);
transaction.commit();
© People Strategists www.peoplestrategists.com Slide 46 of 56
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:
Working with Persistent Objects (Contd.)
transaction.begin();
Employee
empUpdate=(Employee)session.load(Employee.class,
objID);
session.delete(empUpdate);
transaction.commit();
© People Strategists www.peoplestrategists.com Slide 47 of 56
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
© People Strategists www.peoplestrategists.com Slide 48 of 56
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.)
© People Strategists www.peoplestrategists.com Slide 49 of 56
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.)
© People Strategists www.peoplestrategists.com Slide 50 of 56
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.)
© People Strategists www.peoplestrategists.com Slide 51 of 56
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 Hibernate Cache (Contd.)
© People Strategists www.peoplestrategists.com Slide 52 of 56
Hibernate allows you to choose a single cache provider for the whole
application, which are:
Identify Cache provider
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
© People Strategists www.peoplestrategists.com Slide 53 of 56
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
© People Strategists www.peoplestrategists.com Slide 54 of 56
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.)
© People Strategists www.peoplestrategists.com Slide 55 of 56
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.)
© People Strategists www.peoplestrategists.com Slide 56 of 56
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.
Summary (Contd.)

More Related Content

What's hot

Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
Rahul Jain
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Manav Prasad
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
Mumbai Academisc
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
kamal kotecha
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
Lokesh Singrol
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentationJohn Slick
 
Hibernate
HibernateHibernate
Hibernate
Ajay K
 
Spring framework DAO
Spring framework  DAOSpring framework  DAO
Spring framework DAO
Anuj Singh Rajput
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
Lokesh Singrol
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Data access
Data accessData access
Data access
Joshua Yoon
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
Muthuselvam RS
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
Richard Paul
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
Lokesh Singrol
 
TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5
Lokesh Singrol
 

What's hot (19)

Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
jpa-hibernate-presentation
jpa-hibernate-presentationjpa-hibernate-presentation
jpa-hibernate-presentation
 
Hibernate
HibernateHibernate
Hibernate
 
Spring framework DAO
Spring framework  DAOSpring framework  DAO
Spring framework DAO
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Data access
Data accessData access
Data access
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5TY.BSc.IT Java QB U5
TY.BSc.IT Java QB U5
 

Viewers also liked

Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
People Strategists
 
Final Table of Content
Final Table of ContentFinal Table of Content
Final Table of Content
People Strategists
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Krishnakanth Goud
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
Muhammad Zeeshan
 
Hibernate
HibernateHibernate

Viewers also liked (20)

Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
Final Table of Content
Final Table of ContentFinal Table of Content
Final Table of Content
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
RDBMS with MySQL
RDBMS with MySQLRDBMS with MySQL
RDBMS with MySQL
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Basic Hibernate Final
Basic Hibernate FinalBasic Hibernate Final
Basic Hibernate Final
 
JDBC
JDBCJDBC
JDBC
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
Hibernate
HibernateHibernate
Hibernate
 

Similar to Hibernate III

Hibernate Query Language
Hibernate Query LanguageHibernate Query Language
Hibernate Query Language
InnovationM
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
Mahmoud Ouf
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
Mahmoud Ouf
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
kendyhuu
 
Hibernate training mumbai_hql
Hibernate training mumbai_hqlHibernate training mumbai_hql
Hibernate training mumbai_hql
vibrantuser
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
rehaniltifat
 
JPA 2.0
JPA 2.0JPA 2.0
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
Randy Connolly
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving DataAnuchit Chalothorn
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
MuqaddarNiazi1
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
info_zybotech
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
Russell Jurney
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
Russell Jurney
 
MS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmxMS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmx
DataminingTools Inc
 
MS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmxMS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmx
sqlserver content
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
Rohit Radhakrishnan
 

Similar to Hibernate III (20)

Hibernate Query Language
Hibernate Query LanguageHibernate Query Language
Hibernate Query Language
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
Hibernate training mumbai_hql
Hibernate training mumbai_hqlHibernate training mumbai_hql
Hibernate training mumbai_hql
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
JPA 2.0
JPA 2.0JPA 2.0
JPA 2.0
 
ch4
ch4ch4
ch4
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Android App Development 05 : Saving Data
Android App Development 05 : Saving DataAndroid App Development 05 : Saving Data
Android App Development 05 : Saving Data
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
PHP with MYSQL
PHP with MYSQLPHP with MYSQL
PHP with MYSQL
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
 
MS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmxMS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmx
 
MS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmxMS SQL Server: Data mining concepts and dmx
MS SQL Server: Data mining concepts and dmx
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
 

More from People Strategists

Overview of web services
Overview of web servicesOverview of web services
Overview of web services
People Strategists
 

More from People Strategists (7)

Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
CSS
CSSCSS
CSS
 
HTML/HTML5
HTML/HTML5HTML/HTML5
HTML/HTML5
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 

Recently uploaded

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 

Recently uploaded (20)

Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 

Hibernate III

  • 1. © People Strategists www.peoplestrategists.com Slide 1 of 56 Overview of Hibernate -III
  • 2. © People Strategists www.peoplestrategists.com Slide 2 of 56 In this session, you will learn to: Identify Hibernate Query Language (HQL) Implement criteria queries Hibernate cache overview Objectives
  • 3. © People Strategists www.peoplestrategists.com Slide 3 of 56 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
  • 4. © People Strategists www.peoplestrategists.com Slide 4 of 56 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. Identifying HQL (Contd.)
  • 5. © People Strategists www.peoplestrategists.com Slide 5 of 56 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. Creating and Executing Queries Method Description Query Session.createQuery(String queryString) Is used to create a query in the current session by using the specified query string passed as a parameter. Query Query.setComment(String comment) Is used to add the specified comment, passed as a parameter, to the query that invokes this method. Query Query.setString(String name, String val) Is used to bind the string value (second parameter) with the variable (first parameter) in a query at run time. Query Query.setInteger(String name, int val) Is used to bind the integer value (second parameter) with the integer variable (first parameter) in a query at run time.
  • 6. © People Strategists www.peoplestrategists.com Slide 6 of 56 Creating and Executing Queries (Contd.) Method Description Query Query.setLong(String name, long val) Is used to bind the long value (second parameter) with the long variable (first parameter) in a query at run time. Query Query.setFloat(String name, float val) Is used to bind the float value (second parameter) with the float variable (first parameter) in a query at run time. Query Query.setDouble(String name, double val) Is used to bind the double value (second parameter) with the double variable (first parameter) in a query at run time. Query Query.setDate(String name, Date date) Is used to bind the date value (second parameter) 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 setFirstResult(int firstResult) Sets a cursor in the query to retrieve rows starting from the specified index. By default, the index starts from 0.
  • 7. © People Strategists www.peoplestrategists.com Slide 7 of 56 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: Creating and Executing Queries (Contd.) Query query = session.createQuery("FROM EmpDetails");
  • 8. © People Strategists www.peoplestrategists.com Slide 8 of 56 The commonly used clauses in HQL queries are: FROM SELECT AS WHERE ORDER BY GROUP BY Creating and Executing Queries (Contd.)
  • 9. © People Strategists www.peoplestrategists.com Slide 9 of 56 FROM clause is used to load a complete persistent objects into memory. The following code illustrate the FROM clause: 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: Creating and Executing Queries (Contd.) String hql = "FROM Employee"; Query query = session.createQuery(hql); List results = query.list(); String hql = "SELECT E.firstName FROM STUDENT"; Query query = session.createQuery(hql); List results = query.list();
  • 10. © People Strategists www.peoplestrategists.com Slide 10 of 56 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: The AS keyword is optional and you can also be use as shown in the following code: Creating and Executing Queries (Contd.) String hql = "FROM Employee AS E"; Query query = session.createQuery(hql); List results = query.list(); String hql = "FROM Employee E"; Query query = session.createQuery(hql); List results = query.list();
  • 11. © People Strategists www.peoplestrategists.com Slide 11 of 56 WHERE clause is used to narrow the specific objects that are returned from storage. The following code illustrate the WHERE clause: 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: Creating and Executing Queries (Contd.) String hql = "FROM Employee E WHERE E.id = 10"; Query query = session.createQuery(hql); List results = query.list(); String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC"; Query query = session.createQuery(hql); List results = query.list();
  • 12. © People Strategists www.peoplestrategists.com Slide 12 of 56 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: Creating and Executing Queries (Contd.) String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " + "GROUP BY E.firstName"; Query query = session.createQuery(hql); List results = query.list();
  • 13. © People Strategists www.peoplestrategists.com Slide 13 of 56 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: The following code illustrate the use of the count method: Creating and Executing Queries (Contd.) 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 String hql = "SELECT count(distinct E.firstName) FROM Employee E"; Query query = session.createQuery(hql); List results = query.list();
  • 14. © People Strategists www.peoplestrategists.com Slide 14 of 56 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: The following two types of parameter binding is supported by HQL: Named parameters Positional parameters Binding Parameters String hql = "from Employee e where e.ID = '" + ID + "'"; List result = session.createQuery(hql).list();
  • 15. © People Strategists www.peoplestrategists.com Slide 15 of 56 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: 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.) Query query = session.createQuery("FROM Test.BookDetails WHERE author=:var");
  • 16. © People Strategists www.peoplestrategists.com Slide 16 of 56 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: Positional parameters: use question mark (?) to define a named parameter, and need to set parameter according to the position sequence. Binding Parameters (Contd.) String authorname="Rosy"; query.setString("var", authorname); String hql = "from Employee e where e.ID = ? and e.Name = ?"; List result = session.createQuery(hql) .setString(0, "7277") .setParameter(1, "Peter") .list();
  • 17. © People Strategists www.peoplestrategists.com Slide 17 of 56 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: Iterating 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()); }
  • 18. © People Strategists www.peoplestrategists.com Slide 18 of 56 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: Pagination Using Query Method Description Query setFirstResult(int startPosition) This method takes an integer that represents the first row in your result set, starting with row 0. Query setMaxResults(int maxResult) This method tells Hibernate to retrieve a fixed number maxResults of objects.
  • 19. © People Strategists www.peoplestrategists.com Slide 19 of 56 The following code illustrates how you can extend to fetch 10 rows at a time: Pagination Using Query (Contd.) String hql = "FROM Employee"; Query query = session.createQuery(hql); query.setFirstResult(1); query.setMaxResults(10); List results = query.list();
  • 20. © People Strategists www.peoplestrategists.com Slide 20 of 56 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. Using Native SQL Method Description SQLQuery Session.createSQLQuery(String queryString) Is used to create a native SQL query by using the string passed as a parameter. SQLQuery SQLQuery.addEntity(Class entityType) Is used to declare the type of entity that is associated with the table from where the current native SQL query retrieves the data. This method accepts the class name as its parameter.
  • 21. © People Strategists www.peoplestrategists.com Slide 21 of 56 The following code snippet illustrate how to use native SQL in hibernate application: 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. Using Native SQL (Contd.) 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(); .............. }
  • 22. © People Strategists www.peoplestrategists.com Slide 22 of 56 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
  • 23. © People Strategists www.peoplestrategists.com Slide 23 of 56 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: Working with HQL Joins (Contd.) 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]); }
  • 24. © People Strategists www.peoplestrategists.com Slide 24 of 56 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. Implementing Criteria Queries
  • 25. © People Strategists www.peoplestrategists.com Slide 25 of 56 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. Building a Criteria Query Method Description Criteria createCriteria(Class persistenceClass) Is used to create a criteria query for the given entity class. List list() Is used to retrieve the result from a criteria query in a reference of the List collection. Criteria add(Criterion criterion) Is used to add a condition in a criteria query by specifying the condition as a parameter. The condition for a criteria query is specified as an object of the Criterion interface.
  • 26. © People Strategists www.peoplestrategists.com Slide 26 of 56 The following code snippet illustrates the use of the Criteria interface: 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. Criteria criteria = session.createCriteria (Customer.class) List myList = criteria.list(); Building a Criteria Query (Contd.)
  • 27. © People Strategists www.peoplestrategists.com Slide 27 of 56 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: 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 Criteria criteria = session.createCriteria(Customer.class) criteria.add(Restrictions.eq("cust_city", "Dallas")); List myList = criteria.list();
  • 28. © People Strategists www.peoplestrategists.com Slide 28 of 56 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.)
  • 29. © People Strategists www.peoplestrategists.com Slide 29 of 56 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: The employee details are retrieved from a database table where employee balance is greater than $2000. Adding Restrictions (Contd.) Criteria criteria = session.createCriteria(Employee.class) .add(Restrictions.gt("Emp_balance", 2000)); List myList = criteria.list();
  • 30. © People Strategists www.peoplestrategists.com Slide 30 of 56 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: The employee details are retrieved from a database table where employee balance is less than $2000. Adding Restrictions (Contd.) Criteria criteria = session.createCriteria(Employee.class) .add(Restrictions.lt("Emp_balance", 2000)); List myList = criteria.list();
  • 31. © People Strategists www.peoplestrategists.com Slide 31 of 56 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: The customer details are retrieved from a database table where customer name contains character J in their name. Adding Restrictions (Contd.) Criteria criteria = session.createCriteria(Customer.class) .add(Restrictions.like("cust_name", "%J%")) List myList = criteria.list();
  • 32. © People Strategists www.peoplestrategists.com Slide 32 of 56 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: The employee details are retrieved from a database table where employee balance is between $3000 and $5000. Adding Restrictions (Contd.) Criteria criteria = session.createCriteria(Employee.class) .add(Restrictions.between("Emp_balance", new Integer(3000), new Integer(5000))); List myList = criteria.list();
  • 33. © People Strategists www.peoplestrategists.com Slide 33 of 56 The following two methods of the Criteria interface are used for pagination: The following code illustrates how you can extend to fetch 10 rows at a time: Pagination Using Criteria Method Description public Criteria setFirstResult(int firstResult) This method takes an integer that represents the first row in your result set, starting with row 0. public Criteria setMaxResults(int maxResults) This method tells Hibernate to retrieve a fixed number maxResults of objects. Criteria cr = session.createCriteria(Employee.class); cr.setFirstResult(1); cr.setMaxResults(10); List results = cr.list();
  • 34. © People Strategists www.peoplestrategists.com Slide 34 of 56 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: Sorting the Results Using Criteria Criteria cr = session.createCriteria(Employee.class); cr.add(Restrictions.gt("salary", 2000)); crit.addOrder(Order.desc("salary")); List results = cr.list();
  • 35. © People Strategists www.peoplestrategists.com Slide 35 of 56 The following figure depicts the object states. Identifying 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
  • 36. © People Strategists www.peoplestrategists.com Slide 36 of 56 An object passes through various states creation until it is stored in a database. Identifying the Object States (Contd.) The Life Cycle of an Object
  • 37. © People Strategists www.peoplestrategists.com Slide 37 of 56 The Transient State In a Web application, to collect employee details Employee Page EmpID: EmpName: EmpDesig: EmpAddress: Submit Employee object Database
  • 38. © People Strategists www.peoplestrategists.com Slide 38 of 56 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.
  • 39. © People Strategists www.peoplestrategists.com Slide 39 of 56 The Persistent State Transient object saved Database table transformed Persistent object Database identity associated Example: Employee information Databasestore Map the Employee class with a database table in the Hibernate mapping file
  • 40. © People Strategists www.peoplestrategists.com Slide 40 of 56 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 Persistent State (Contd.)
  • 41. © People Strategists www.peoplestrategists.com Slide 41 of 56 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. The Detached State
  • 42. © People Strategists www.peoplestrategists.com Slide 42 of 56 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: Working with Persistent Objects Database retrieve store Implement different operations Persist object Retrieve data Update data Delete object
  • 43. © People Strategists www.peoplestrategists.com Slide 43 of 56 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: Working with Persistent Objects (Contd.) Employee emp = new Employee(); emp.setEmpID(...); emp.setEmpName( ... ); ............... ............... Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Serializable objId = session.save(emp); tx.commit();
  • 44. © People Strategists www.peoplestrategists.com Slide 44 of 56 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: Working with Persistent Objects (Contd.) 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(); transaction.begin(); Employee empUpdate=(Employee)session.load(Employee.class, objID); empUpdate.setAddress("Hudson Street, California"); .............. transaction.commit();
  • 45. © People Strategists www.peoplestrategists.com Slide 45 of 56 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: Working with Persistent Objects (Contd.) .............. transaction.begin(); Employee empUpdate=(Employee)session.load(Employee.class, objID); empUpdate.setAddress("Hudson Street, California"); session.update(empUpdate); transaction.commit();
  • 46. © People Strategists www.peoplestrategists.com Slide 46 of 56 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: Working with Persistent Objects (Contd.) transaction.begin(); Employee empUpdate=(Employee)session.load(Employee.class, objID); session.delete(empUpdate); transaction.commit();
  • 47. © People Strategists www.peoplestrategists.com Slide 47 of 56 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
  • 48. © People Strategists www.peoplestrategists.com Slide 48 of 56 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.)
  • 49. © People Strategists www.peoplestrategists.com Slide 49 of 56 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.)
  • 50. © People Strategists www.peoplestrategists.com Slide 50 of 56 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.)
  • 51. © People Strategists www.peoplestrategists.com Slide 51 of 56 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 Hibernate Cache (Contd.)
  • 52. © People Strategists www.peoplestrategists.com Slide 52 of 56 Hibernate allows you to choose a single cache provider for the whole application, which are: Identify Cache provider 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
  • 53. © People Strategists www.peoplestrategists.com Slide 53 of 56 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
  • 54. © People Strategists www.peoplestrategists.com Slide 54 of 56 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.)
  • 55. © People Strategists www.peoplestrategists.com Slide 55 of 56 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.)
  • 56. © People Strategists www.peoplestrategists.com Slide 56 of 56 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. Summary (Contd.)