Hibernate III

56
© People Strategists www.peoplestrategists.com Slide 1 of 56 Overview of Hibernate -III

Transcript of Hibernate III

Page 1: Hibernate III

© People Strategists www.peoplestrategists.com Slide 1 of 56

Overview of Hibernate -III

Page 2: 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

Page 3: Hibernate III

© 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

Page 4: Hibernate III

© 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.)

Page 5: Hibernate III

© 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 Queryinterface.

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.

Page 6: Hibernate III

© 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.

Page 7: Hibernate III

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

Page 8: Hibernate III

© 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.)

Page 9: Hibernate III

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

Page 10: Hibernate III

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

Page 11: Hibernate III

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

Page 12: Hibernate III

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

Page 13: Hibernate III

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

Page 14: Hibernate III

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

Page 15: Hibernate III

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

Page 16: Hibernate III

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

Page 17: Hibernate III

© 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 Queryinterface 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());

}

Page 18: Hibernate III

© 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.

Page 19: Hibernate III

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

Page 20: Hibernate III

© 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 SQLQueryinterface 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.

Page 21: Hibernate III

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

..............

}

Page 22: Hibernate III

© 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

Page 23: Hibernate III

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

}

Page 24: Hibernate III

© 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

Page 25: Hibernate III

© 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 Criteriainterface.

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.

Page 26: Hibernate III

© 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.)

Page 27: Hibernate III

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

Page 28: Hibernate III

© 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.)

Page 29: Hibernate III

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

Page 30: Hibernate III

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

Page 31: Hibernate III

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

Page 32: Hibernate III

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

Page 33: Hibernate III

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

Page 34: Hibernate III

© People Strategists www.peoplestrategists.com Slide 34 of 56

The Criteria API provides the org.hibernate.criterion.Orderclass 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();

Page 35: Hibernate III

© 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

Page 36: Hibernate III

© 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

Page 37: Hibernate III

© 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:

SubmitEmployee

object

Database

Page 38: Hibernate III

© 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.

Page 39: Hibernate III

© People Strategists www.peoplestrategists.com Slide 39 of 56

The Persistent State

Transient object

saved Databasetable

transformed

Persistentobject

Database identityassociated

Example:

Employeeinformation

Databasestore

Map the Employee class with a database table in

the Hibernate mapping file

Page 40: Hibernate III

© 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.)

Page 41: Hibernate III

© 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

Page 42: Hibernate III

© 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

Databaseretrieve

store Implement different

operations

Persist object

Retrieve data

Update data

Delete object

Page 43: Hibernate III

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

Page 44: Hibernate III

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

Page 45: Hibernate III

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

Page 46: Hibernate III

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

Page 47: Hibernate III

© 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

Page 48: Hibernate III

© 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.)

Page 49: Hibernate III

© 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 thesecond-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.)

Page 50: Hibernate III

© 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.)

Page 51: Hibernate III

© 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.)

Page 52: Hibernate III

© 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

EHCacheIt can cache in memory or on disk and clustered caching and it supports the optional Hibernate query result cache.

OSCacheSupports caching to memory and disk in a single JVM, with a rich set of expiration policies and query cache support.

warmCacheA 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 JGroupsmulticast library. It supports replication or invalidation, synchronous or asynchronous communication, and optimistic and pessimistic locking. The Hibernate query cache is supported

Page 53: Hibernate III

© 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

Page 54: Hibernate III

© 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.)

Page 55: Hibernate III

© 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.Restrictionsclass 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.)

Page 56: Hibernate III

© 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.)