Detailed introduction about criteria API in hibernate

Posted By : Himanshu Kumar | 31-Jul-2018

Introduction :-

Hibernate underpins an element that causes us to fabricate queries powerfully. The org.hibernate.Criteria is the interface utilized for this reason. Criteria is valuable when we should apply a various confounded inquiry criteria on the queries.

 

For a Criteria query, a Criterion Object ought to be developed (i.e) a call to createCriteria() passing the class of the items we need the inquiry to return.

 

Why Hibernate Criteria :-

Presently HQL (Hibernate Query Language) is utilized broadly to question information utilizing Hibernate. In any case, there are numerous disadvantages, for example,


1. SQL-like punctuation and Non Extensible 

2. Social system rather than OO technique 

3. Issue in making seek inquiries on the fly 

4. Multifaceted nature increments with number of variable conditions 

5. Mistake inclined String link 

6. Coordinate utilization of question parameters in the inquiry string .

 

A simple example of hibernate query :-

 

 

String query = "select o from Order as o join o.products as p where o.priceTotal > :priceTotalLower and o.priceTotal < :priceTotalUpper";           
Query q = sess.createQuery(query);
q.setDouble("priceTotalLower", Double.parseDouble(lower));
q.setDouble("priceTotalUpper",Double.parseDouble(upper));
List list = q.list()

 

In contrast with the Criteria API, the above question gets diminished to straightforward two lines with more perception and comprehension of the usefulness

 

List list = sess.createCriteria(Order.class)
.add(Restrictions.between(lower,upper).list();


Notwithstanding the succinctness and decipherability, following are a portion of the best parts of utilizing the Criteria API

1. Parts of the social approach 
2. Lessens the multifaceted nature
3. Multi-criteria look functionalities
4. Building Hibernate Queries on the fly 
5. Learning of SQL a bit much
6. Extensible since it utilizes OO approach
7. Interoperable since it has arrangement for including local SQL provisos too 
8. Rich arrangement of examination administrators
9. Business Objects as question parameters, without using essential and outside key references 
10. Upgrading inquiries by giving different JOIN Strategies
11. Gives cleaner, clearer, more dependable and more viable code.

 

Description about criteria API in hibernate :-

 

Core components present in the Criteria API.


1. Criteria

2. Criterion

3. Restrictions

4. Projection

5. Order

 

Criteria class furnishes the passage to working with criteria APIs. Rule class is the protest arranged portrayal of the social model. Confinement API gives the implicit kinds to Criterion. Basically, the Restriction class is a processing plant to the Criterion class. The greater part of its techniques are static.

 

In Hibernate 2.x, the Expression class gave the administrations that are currently given by the Restriction class. The Restriction class gives all the required limitations, for example, squares with (eq()), intelligent and (and()), (like()) Aggregation and Grouping are given by the Projection class. Request class speaks to the "request by" provision of SQL.


Order interface :-

In HQL (and SQL), the request by condition enables you to arrange your inquiry comes about. This is finished utilizing the addOrder() strategy and the Order class The SQL will have the request proviso in the arrangement the Order objects were added to the Critieria.

 

Criteria crit = session.createCriteria(Sale.class) ;
crit.addOrder( Order.desc("date") );
crit.addOrder( Order.asc("product.number") );

 

Simple Criteria Query:-

 

The accompanying code indicates how a straightforward Criteria inquiry is manufactured.

 

1 .It chooses the Insurance Object

2. Incorporates a Where provision protection name like '%a%'

3. Incorporates another Where proviso investmentAmount esteem in the vicinity of 1000 and 2500 comprehensive

4. Sets the quantity of most extreme outcomes as 5

 
 

session = sessionFactory.openSession();
Criteria crit = session.createCriteria(Insurance.class);
crit.add(Restrictions.like("insuranceName", "%a%")); 
crit.add(Expression.between("investAmount", new Integer(1000),new Integer(2500))); 
crit.setMaxResults(5); 
List insurances = crit.list();
for(Iterator it =insurances.iterator();it.hasNext();){
	Insurance insurance = (Insurance) it.next();
  System.out.println("ID: " + insurance.getLngInsuranceId());
  System.out.println("Name: " + insurance.getInsuranceName());
  System.out.println("Amount: " + insurance.getInvestAmount());
}

 

Criterion Chaining

This is a well known strategy for including Restrictions, Expressions, Projections and Order question without the need to make extra Objects. This is especially helpful when the Criteria Objects which are extensible are should have been passed between techniques.

 

 

List sales = session.createCriteria(Sale.class)
    .add(Expression.ge("date",startDate)
    .add(Expression.le("date",endDate)
    .addOrder( Order.asc("date") )
    .setFirstResult(0)
    .setMaxResults(10)
    .list();

 

WHERE property is restricted in this case :-

The WHERE provision or Restrictions can be effortlessly connected by means of Restriction.eqProperty(), Restriction.neProperty(), Restriction.leProperty() and Restriction.geProperty()

 

// Adds a WHERE Clause for comparing two columns,
session.createCriteria(Sale.class)
    .eqProperty("saleDate","releaseDate")
    .list();

 

Confinement still permits custom limitations included utilizing Restrictions.sqlRestriction

 

// Adds a native SQL Restriction in the WHERE Clause
sess.createCriteria(Cat.class)
.add(Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Fritz%",Hibernate.STRING) ) .list();

 

All the static techniques accessible in Restrictions are additionally accessible in the Expression API. Likewise it contains some extra strategies, for example, ilike("columnname") which completes a lower(columnname) in the inquiry.

 

Disjunction and Conjunction:-

 

Disjunction and Conjunction are magnificent APIs which help perform complex pursuit criteria easy to create and keep up.

 

Disjunction disList = Restrictions.disjunction();
disList.add(Restrictions.eq("id",new Integer(1));
disList.add(Restrictions.eq("id",new Integer(2));
sess.createCriteria(Cat.class) .add(disList);
// This gives the WHERE Clause WHERE (id=1 OR id=2)

 

Conjunction shows a gathering of Critierion to be ANDed

 

 

Conjunction conList = Restrictions.conjunction();
conList.add(Restrictions.eq("id",new Integer(1));
conList.add(Restrictions.eq("id",new Integer(2));
sess.createCriteria(Cat.class) .add(conList);
// This gives the WHERE Clause WHERE (id=1 AND id=2)

 

_The Disjunctions and Conjunctions can be settled too and furthermore alongside gathering of Restrictions.

 

Conjunction conList = Restrictions.conjunction();
conList.add(Restrictions.disjunction() .add(Restrictions.eq("id",new Integer(1))));

 

The most effective method to join Tables utilizing Criteria API

Utilizing HQLs, joins look like SQL intently.

 

// use LEFT JOIN FETCH for optimizing queries
from Sale sale where sale.date > :startDate left join fetch sale.product

 

The same can be accomplished utilizing Criteria API with the assistance of setFetchMode()

 

session.createCriteria(Sale.class)
      .setFetchMode("product",FetchMode.EAGER)
      .setFetchMode("category",FetchMode.EAGER)
      .list();

 

Utilizing Criteria API, even Restriction can be connected on the joined tables.Criteria API utilizes the createCriteria() or createAlias() (no new example) to make an inward join between the two tables.

 


// to find all the shirt models with sizes over 40.
// HQL: from Shirt shirt join shirt.availableSizes size where size.number > 40

Session.createCriteria(Shirt.class)
      .createCriteria("availableSizes")
      .add(Expression.gt("number", new Integer(40)))
      .list();

 

Projections - Aggregation and Grouping

 

The Projections API is utilized for accumulation and gathering usefulness. A basic case which restores the tally of number of felines with age more noteworthy than 10.

 

// Simple Projection
session.createCriteria(Cat.class)
      .add(Restrictions.gt("age", new Integer(10))
      .setProjection(Projections.rowCount())
      .list();

 

Various collections should be possible in a solitary Criteria and should be possible alongside a gathering by proviso.

 

Criteria crit = session.createCriteria(Cat.class)
ProjectionList projList = Projections.projectionList();
projList.add(Projections.rowCount() );
projList.add(Projections.avg("weight") ) ;
projList.add(Projections.max("weight") ) ;
projList.add(Projections.groupProperty("color") ) ) ;
List result = crit.setProjection(projList).list();

 

To enable the clients to question just the required sections Hibernate 3 presented the Projections.property()

 
 
 

Criteria crit = session.createCriteria(Employee.class);
crit.add(Restrictions.eq("zipCode", zipCode));
crit.add(Restrictions.gt("salary", new Integer(10000));
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("name"));
projList.add(Projections.property("age"));
projList.add(Projections.property("county"));
projList.add(Projections.property("job"));
crit.setProjection(projList);

 

This truly helps when the table being questioned contains 50 to 60 segments and we require just 4 to 5 sections.

 

Implementation of  Example API for query :-

 

The Example API upgrades the question by introducing the content qualities and by giving extensibility of the Criterion Object.

 

 

 

// Initializing the text values to be used
Accommodation accommodationEx = new Accommodation();
accommodationEx.setCountry(country);
accommodationEx.setCapacity(capacity);

// Creating and fine tuning the example object
Example example = Example.create(accommodationEx)
    .ignoreCase() //Queries are case insensitive
    .excludeZeroes()  //zero-valued fields are ignored
    .excludeProperty("doNotUse") // this property is excluded
    .enableLike(MatchMode.ANYWHERE); //query string matching uses ‘%X%’

// Using the Example Object and adding further restrictions
List list = session.createCriteria(Accommodation.class)
    .add(example)
    .add(Expression.between("availabilityDate", startDate, endDate))
    .list();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

About Author

Author Image
Himanshu Kumar

Himanshu Kumar is a seasoned Backend Developer with extensive experience in the industry. He has a deep understanding and hands-on expertise in a range of technologies, including Core Java, Spring-Boot, Hibernate, Apache Kafka messaging queue, and blockchain development with Ethereum, Tron, and smart contract development. He is also well-versed in relational databases like MySQL and PostgreSQL. His proficiency in API implementation, web services, development testing, and deployment has contributed to the successful delivery of various client projects, such as Wethio Exchange, Hedgex Exchange, Envoychain payment gateway based on Stellar assets, and more. With a creative mind and excellent analytical skills, Himanshu enjoys staying up to date with the latest technologies and exploring new ideas to bring value to his work.

Request for Proposal

Name is required

Comment is required

Sending message..