Upload
er-gaurav-kumar
View
18
Download
1
Embed Size (px)
Citation preview
HibernateGETTING STARTED WITH HIBERNATE CRITERIA
- BY GAURAV KUMAR
Introduction
The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kind of filtration rules and logical conditions. And the Session provides the createCriteria() API – which can be used to create a Criteria object that returns instances of the persistence object’s class when we execute a query.
Sample Class for Examples
public class Item implements Serializable { private Integer itemId; private String itemName; private String itemDescription; private Integer itemPrice; // standard setters and getters}
How to create criteria Object?
Session session = HibernateUtil.getHibernateSession();
Criteria cr = session.createCriteria(Item.class);cr.add(Restrictions.like("itemName", "%item One%")); List results = cr.list();
The above query is a simple demonstration of how to get all the items. Let’s see what was done, step by step:
Create a session object of type Session Create an instance of Session from the SessionFactory object Create an instance of Criteria by calling the createCriteria() method Call the list() method of the criteria object which gives us the results
Sample Codes?
The add() method can be used with Criteria object to add restriction for a criteria query. For that we also need to use the Restriction class.
The following code snippet of code contains all the available functionalities available with Restriction class:
To get items having price more than 1000: cr.add(Restrictions.gt("itemPrice", 1000));To get items having itemPrice less than 1000: cr.add(Restrictions.lt("itemPrice", 1000));
To get items having itemNames start with Chair: cr.add(Restrictions.like("itemName", "chair%"));Case sensitive form of the above restriction: cr.add(Restrictions.ilike("itemName", "Chair%"));Case sensitive with matching the pattern in between: cr.add(Restrictions.ilike("itemName", "Chair%“, MatchMode.ANYWHERE));
To get records having itemPrice in between 100 and 200: cr.add(Restrictions.between("itemPrice", 100, 200));
To check if the given property is null: cr.add(Restrictions.isNull("itemDescription"));
To check if the given property is not null: cr.add(Restrictions.isNotNull("itemDescription"));
What if I want to add two or more conditions???
Now inevitably the question comes, whether we can combine two or more of the above comparisons or not. The answer is of course yes – the Criteria API allows us to easily chain restrictions:
cr.add(Restrictions.isNotEmpty("itemDescription")).add(Restrictions.like("itemName", "chair%"));
To add two restrictions with logical operations:Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); Criterion chairItems = Restrictions.like("itemName", "Chair%");
To get items with the above defined conditions joined with Logical OR:LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); cr.add(orExample);
Sorting of the result
Now that we know the basic usage of Criteria, let’s have a look at the sorting functionalities of Criteria.
In the following example we order the list in an ascending order of the name and then in a descending order of the price:
List sortedItems = cr.addOrder(Order.asc("itemName")).addOrder(Order.desc("itemPrice")).list();
In the next section we will have a look at how to do aggregate functions.
Projections, Aggregates And Grouping Functions
Now let’s have a look at the different aggregate functions:
Set projections:List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).add( Restrictions.eq("itemPrice", 12000)).list();
The following is an example of aggregate functions:
Aggregate function for Average:List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList() .add(Projections.avg("itemPrice"))).list();
Advantages over HQL???
ANY GUESS???
Here are some of the advantages???
Clearly, the main and most hard-hitting advantage of Criteria queries over HQL is the nice, clean, Object Oriented API.
We can simply write more flexible, dynamic queries compared to plain HQL. The logic can be refactored with the IDE and has all the type-safety benefits of the Java language itself.
There are of course some disadvantages as well, especially around more complex joins. So, generally speaking, we’ll have to use the best tool for the job – that can be the Criteria API in
most cases, but there are definitely cases where we’ll have to go lower level.
Questions???
Feel free to write : [email protected].