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

Multi Row Operations: Hibernate Query Language Criteria API

Hibernate provides several techniques for performing bulk operations on data in the database, including the Hibernate Query Language (HQL), Criteria API, and native SQL. HQL is the most popular as it allows database-independent queries written in terms of objects and properties rather than tables and columns. HQL queries are translated into the underlying SQL and parameters can be passed positionally or by name. Results are returned as serializable collections rather than result sets for use across the network.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views41 pages

Multi Row Operations: Hibernate Query Language Criteria API

Hibernate provides several techniques for performing bulk operations on data in the database, including the Hibernate Query Language (HQL), Criteria API, and native SQL. HQL is the most popular as it allows database-independent queries written in terms of objects and properties rather than tables and columns. HQL queries are translated into the underlying SQL and parameters can be passed positionally or by name. Results are returned as serializable collections rather than result sets for use across the network.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Multi Row Operations

Hibernate Query Language


Criteria API
Bulk operations related techniques
• In order to manipulate single row operations by
taking our choice value as criteria value or to
manipulate more than one row at a time then we
can use one of the following techniques:
1. HQL [Hibernate query language]
2. Criteria API
3. Native SQL
Note: HQL is the most popular persistent technique
in hibernate programming.
HQL
• Queries are database independent queries.
• HQL queries should be written based on pojo
classes and member variables of pojo classes.
• HQL queries are object level queries. So they
return hibernate pojo class objects as results.
• HQL queries and keywords are similar to queries of
oracle.
• Hibernate s/w converts hql queries into sql queries
and sends them to database s/w for execution.
HQL vs. SQL
• Ex1:
• Sql> select * from employee; [Here employee is table name]
• Hql>from EmpBean
or
• Hql>from EmpBean eb
Or
• Hql>From EmpBean as eb
Or
• Hql> select eb from EmpBean as eb [Here EmpBean is pojo class and eb
is alias name]
• Note: When select keyword is there or pojo class member variables
are there in a hql query then creating alias name for pojo class is
mandatory operation.
Ex2
• Sql> select eid, lastname from employee where
eid >= 100;
• Hql>select eb.eid, eb.lastname from EmpBean as
eb where eb.eid >= 100
Note:
1 hql keywords and queries are not case sensitive
but pojo class name and pojo class member
variable names used in hql are case sensitive.
2 string values in hql query should be represented
in single quotes. Eg: ‘Sai’, ‘Kanakadhar’ etc..,
Ex3:
• Sql> select count (*) from employee;
• Hql> select count (*) from EmpBean
Ex4:
• Sql>delete from employee where firstname in (‘Bucky’, ‘Wall’);
• Hql>delete from EmpBean as eb where eb.firstname in
(‘Bucky’, ‘Wall’)
• To execute select queries of hql use list() or iterate() on query
object.
• To select non-select statement hql queries call
executeUpdate() on query object.
• Execution of hql query is nothing but converting hql query to
the underlying database s/w specific sql query & sending that
sql query to database s/w for execution.
• Hibernate 3.x software internally uses AST query translator
factory to convert hql queriesn into database specific s/w
equivalent sql queries.
Sql select queries of jdbc vs hql select queries of hibernate

• Jdbc code based select queries execution gives ResultSet


object which is not serializable object. So we cannot send
ResultSet object over the network.
• Hibernate based select hql queries execution gives results in
the form of collection framework List data
• structure. Since this List data structure is serializable object
by default we can send it through network.
• Note: All collection frame work data structures are
serializable by default.
• Note: In order to make pojo class object as serializable
object, pojo class should implement java.io.Serializable
interface.
• Parameters passed to hql query never makes hql query as pre
compiled query because hql query cannot directly go to database
s/w.
• In most of the cases hibernate s/w generates jdbc code internally
& uses pre-compiled sql queries with the support of prepared
statement objects to perform persistent operations on the table.
Note: All HQL queries related to sql queries generated by hibernate
s/w are pre compiled queries by default.
• We cannot pass hql keywords, pojo class names or pojo class
member variables names as values of parameters to hql queries.
• Use parameters in hql query only to pass input values and
condition values.
• In jdbc programming we do not have named parameters. But in
hql programming we have concept of both positional and named
parameters and both can also be used in a single query. But we
must pass positional parameters before named parameters.
list() vs iterate()
• list() generates results by selecting all the records through the
execution of a single select sql query [no lazy loading]
• iterate() selects the records from database table by executing a
separate query to read each record and a
• separate query to read all id values. [Lazy loading]
• Eg: If we read 10 records from table then list() generates one query
where as iterate() generates 11
• queries [one for id values & 10 queries for 10 records].
Note:
1. We can see difference between list() and iterate() only when hql
select queries are selecting all the columns of a table.
2 When iterate() is used to select specific columns values then lazy
loading doesn’t takes place.
Examples
1. Selecting all columns using list() [early loading]
String qry = "select st from StudentBean as st";
Query q1 = ses.createQuery(qry);
List l = q1.list();
System.out.println("Records are: ");
for( int i = 0; i < l.size() ; i++) //for each row
{
StudentBean stu = (StudentBean) l.get(i);
System.out.println(stu.getSid()+" "+stu.getSname()+"
"+stu.getTot_m());
}
2. SelectAllCols-Iterator[Lazy loading]
String qry = "select st from StudentBean as st";
Query q1 = ses.createQuery(qry);
Iterator it = q1.iterate(); //reads only id values [primary key values of
all query satisfied records
System.out.println("Records are: ");
while(it.hasNext()) //for each row
{
StudentBean stu = (StudentBean) it.next(); //generates a separate
query to fetch eacjh record
System.out.print(stu.getSid()+" "+stu.getSname()+" "+stu.getTot_m()
System.out.println();
}
3. SelectFewCols-List
String qry = "select st.sid, st.sname from StudentBean as st";
Query q1 = ses.createQuery(qry);
List l = q1.list();
System.out.println("Records are: ");
for( int i = 0; i < l.size() ; i++) //for each row
{
Object row[] = (Object[]) l.get(i);
for( int j = 0; j < row.length ; j++) //for each column
{
System.out.print(row[j].toString()+" ");
}
System.out.println();
}
4. Conditional Select
String qry = "select st.sid, st.sname from
StudentBean as st where st.sid > 2";
String qry = "select st from StudentBean as st
where st.sid > 1 and st.sname like '_a%'";
String qry = "select st.sid, st.sname from
StudentBean as st where (st.sid > 4) or (st.sname
like 'S%') or (st.sname like ‘Samantha%')";
Multiple values

String qry = "select count(*), avg(st.tot_m), sum(st.tot_m),


max(st.tot_m), min(st.tot_m) from StudentBean st";
Query q1 = ses.createQuery(qry);
List l = q1.list();
Object ob[] = (Object[]) l.get(0);
System.out.println("Count is: "+ob[0].toString());
System.out.println("Avg is: "+ob[1].toString());
System.out.println("Sum is: "+ob[2].toString());
System.out.println("Max is: "+ob[3].toString());
System.out.println("Min is: "+ob[4].toString());
5. Aggregate functions
Single value
String qry = "select count(*) from StudentBean";
Query q1 = ses.createQuery(qry);
List l = q1.list();
System.out.println("Total Records are:
"+l.toString());
6. subqueries
String qry = "select st from StudentBean as st
where st.tot_m = (select max(st.tot_m)
from StudentBean as st)";
Query q1 = ses.createQuery(qry);
List l = q1.list();
Input values to hql queries

• To make hql queries flexible by setting input


values of query from outside the query and to
set query input values without bothering
about database s/w, we can pass parameters
to hql queries in java style.
Parameters in HQL queries

1. Positional parameters (?)


2. Named Parameters (:<name>)
[Recommended to use]
a. Positional Parameters
String qry = "select st from StudentBean as st
where st.tot_m >= ? and st.sname like ?";
Query q1 = ses.createQuery(qry);
//setting parameter values
q1.setInteger(0, 98); //index starts with 0 [zero]
q1.setString(1, "S%");
List l = q1.list();
b. Named Parameters
String qry = "select st from StudentBean as st
where st.tot_m >= :tm and st.sname like :sn";
Query q1 = ses.createQuery(qry);
//setting parameter values
q1.setInteger("tm", 98);
q1.setString("sn", "S%");
List l = q1.list();
C. Combination [once we start named parameter we
cannot go for positional parameters]
String qry = "select st from StudentBean as st where
st.tot_m >= ? or st.sname like ? or st.sname in(?, :n2)";
Query q1 = ses.createQuery(qry);
//setting parameter values
q1.setInteger(0, 98);
q1.setString(1, "N%");
q1.setString(2, "Sai");
q1.setString("n2", "Rajini");
List l = q1.list();
9. Named Queries
a. select
in mapping file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="StudentBean" table="student">
<id name="sid" column = "sid"/>
<property name="sname"
column="sname"/>
<property name="tot_m" column = "tot_m"/>
</class>
<query name = "qry">
select st from StudentBean as st where st.sname like :n
</query>
</hibernate-mapping>
Client program:
Query q1 = ses.getNamedQuery("qry");
q1.setString("n", "S%");
//Execution of native sql query
List l = q1.list();
b. Delete
In mapping file:
<query name = "qry">
delete from StudentBean as st where st.tot_m = :m
</query>
In client program:
Query q1 = ses.getNamedQuery("qry");
q1.setFloat("m", 99.9f);
int res = q1.executeUpdate();
System.out.println("Records deleted are: "+res);
10. Non-Select-Transactional
a. Update
String qry = "update StudentBean as st set
st.tot_m = st.tot_m + ? where st.tot_m < :m";
Query q1 = ses.createQuery(qry);
q1.setInteger(0, 1);
q1.setFloat("m", 102.0f);
int count = q1.executeUpdate();
System.out.println("No of records updated are:
"+count);
b. Delete
String qry = "delete from StudentBean as st
where st.sid = (select min(st.sid) from
StudentBean st)";
Query q1 = ses.createQuery(qry);
int count = q1.executeUpdate();
System.out.println("No of records deleted are:
"+count);
c. Insert [in HQL we cannot insert end user given
input values. But we can read records from
source table and we can insert into destination
table.]
Note: In HQL it is not possible to insert one table
records into another table
Note: Here we need two pojo classes. One for source table and
another for destination table. Here
StuBean is for destination and StudentBean is for source. Data
types of corresponding columns of both
the tables should be same.
String qry = "insert into StuBean (sid1, sname1, tot_m1) select
st.sid, st.sname, st.tot_m
from StudentBean as st where st.tot_m >= :tm";
Query q1 = ses.createQuery(qry);
//setting values for marks
q1.setFloat("tm", 98.0f);
int count = q1.executeUpdate();
System.out.println("No of records inserted into stu table are:
"+count);
Criteria API
• Hibernate provides alternate ways of manipulating
objects and in turn data available in RDBMS tables. One
of the methods is Criteria API which allows you to build
up a criteria query object programmatically where you
can apply filtration rules and logical conditions.
• The Hibernate Session interface
provides createCriteria() method which can be used to
create a Criteria object that returns instances of the
persistence object's class when your application
executes a criteria query.
Example
Following is the example of a criteria query is one
which will simply return every object that
corresponds to the Employee class

Criteria cr = session.createCriteria(Employee.class);
List results = cr.list();
Restrictions with Criteria
We can use add() method available
for Criteria object to add restriction for a criteria
query.
Following is the example to add a restriction to
return the records with salary is equal to 2000
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();
More Examples
Criteria cr = session.createCriteria(Employee.class);

// To get records having salary more than 2000


cr.add(Restrictions.gt("salary", 2000));
// To get records having salary less than 2000
cr.add(Restrictions.lt("salary", 2000));
// To get records having fistName starting with zara
cr.add(Restrictions.like("firstName", "zara%"));
// Case sensitive form of the above restriction.
cr.add(Restrictions.ilike("firstName", "zara%"));
// To get records having salary in between 1000 and 2000
cr.add(Restrictions.between("salary", 1000, 2000));
// To check if the given property is null
cr.add(Restrictions.isNull("salary"));
// To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"));
// To check if the given property is empty
cr.add(Restrictions.isEmpty("salary"));
// To check if the given property is not empty
cr.add(Restrictions.isNotEmpty("salary"));
Using AND OR operators
Criteria cr = session.createCriteria(Employee.class);

Criterion salary = Restrictions.gt("salary", 2000);


Criterion name = Restrictions.ilike("firstNname","zara%");
// To get records matching with OR condistions
LogicalExpression orExp = Restrictions.or(salary, name);
cr.add( orExp );
// To get records matching with AND condistions
LogicalExpression andExp = Restrictions.and(salary, name);
cr.add( andExp );
List results = cr.list();
Sorting the Results

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. This example demonstrates how you
would use the Order class to sort the result set
Criteria cr = session.createCriteria(Employee.class);
// To get records having salary more than 2000
cr.add(Restrictions.gt("salary", 2000));

// To sort records in descening order


crit.addOrder(Order.desc("salary"));

// To sort records in ascending order


crit.addOrder(Order.asc("salary"));

List results = cr.list();


Projections & Aggregations:

The Criteria API provides


the org.hibernate.criterion.Projections class
which can be used to get average, maximum or
minimum of the property values. The
Projections class is similar to the Restrictions
class in that it provides several static factory
methods for obtaining Projection instances.
Criteria cr = session.createCriteria(Employee.class);
// To get total row count.
cr.setProjection(Projections.rowCount());
// To get average of a property.
cr.setProjection(Projections.avg("salary"));
// To get distinct count of a property.
cr.setProjection(Projections.countDistinct("firstName"));
// To get maximum of a property.
cr.setProjection(Projections.max("salary"));
// To get minimum of a property.
cr.setProjection(Projections.min("salary"));
// To get sum of a property.
cr.setProjection(Projections.sum("salary"));
Fetching Few Columns
Criteria cr = session.createCriteria(User.class)
.setProjection(Projections.projectionList()
.add(Projections.property("id"), "id")
.add(Projections.property("Name"), "Name"))
.setResultTransformer(Transformers.aliasToBean(Us
er.class));

List<User> list = cr.list();


Second Level Cache in Hibernate

You might also like