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 [Link], [Link] from EmpBean as
eb where [Link] >= 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 [Link] 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 [Link]
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 = [Link](qry);
List l = [Link]();
[Link]("Records are: ");
for( int i = 0; i < [Link]() ; i++) //for each row
{
StudentBean stu = (StudentBean) [Link](i);
[Link]([Link]()+" "+[Link]()+"
"+stu.getTot_m());
}
2. SelectAllCols-Iterator[Lazy loading]
String qry = "select st from StudentBean as st";
Query q1 = [Link](qry);
Iterator it = [Link](); //reads only id values [primary key values of
all query satisfied records
[Link]("Records are: ");
while([Link]()) //for each row
{
StudentBean stu = (StudentBean) [Link](); //generates a separate
query to fetch eacjh record
[Link]([Link]()+" "+[Link]()+" "+stu.getTot_m()
[Link]();
}
3. SelectFewCols-List
String qry = "select [Link], [Link] from StudentBean as st";
Query q1 = [Link](qry);
List l = [Link]();
[Link]("Records are: ");
for( int i = 0; i < [Link]() ; i++) //for each row
{
Object row[] = (Object[]) [Link](i);
for( int j = 0; j < [Link] ; j++) //for each column
{
[Link](row[j].toString()+" ");
}
[Link]();
}
4. Conditional Select
String qry = "select [Link], [Link] from
StudentBean as st where [Link] > 2";
String qry = "select st from StudentBean as st
where [Link] > 1 and [Link] like '_a%'";
String qry = "select [Link], [Link] from
StudentBean as st where ([Link] > 4) or ([Link]
like 'S%') or ([Link] 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 = [Link](qry);
List l = [Link]();
Object ob[] = (Object[]) [Link](0);
[Link]("Count is: "+ob[0].toString());
[Link]("Avg is: "+ob[1].toString());
[Link]("Sum is: "+ob[2].toString());
[Link]("Max is: "+ob[3].toString());
[Link]("Min is: "+ob[4].toString());
5. Aggregate functions
Single value
String qry = "select count(*) from StudentBean";
Query q1 = [Link](qry);
List l = [Link]();
[Link]("Total Records are:
"+[Link]());
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 = [Link](qry);
List l = [Link]();
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 [Link] like ?";
Query q1 = [Link](qry);
//setting parameter values
[Link](0, 98); //index starts with 0 [zero]
[Link](1, "S%");
List l = [Link]();
b. Named Parameters
String qry = "select st from StudentBean as st
where st.tot_m >= :tm and [Link] like :sn";
Query q1 = [Link](qry);
//setting parameter values
[Link]("tm", 98);
[Link]("sn", "S%");
List l = [Link]();
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 [Link] like ? or [Link] in(?, :n2)";
Query q1 = [Link](qry);
//setting parameter values
[Link](0, 98);
[Link](1, "N%");
[Link](2, "Sai");
[Link]("n2", "Rajini");
List l = [Link]();
9. Named Queries
a. select
in mapping file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"[Link]
<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 [Link] like :n
</query>
</hibernate-mapping>
Client program:
Query q1 = [Link]("qry");
[Link]("n", "S%");
//Execution of native sql query
List l = [Link]();
b. Delete
In mapping file:
<query name = "qry">
delete from StudentBean as st where st.tot_m = :m
</query>
In client program:
Query q1 = [Link]("qry");
[Link]("m", 99.9f);
int res = [Link]();
[Link]("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 = [Link](qry);
[Link](0, 1);
[Link]("m", 102.0f);
int count = [Link]();
[Link]("No of records updated are:
"+count);
b. Delete
String qry = "delete from StudentBean as st
where [Link] = (select min([Link]) from
StudentBean st)";
Query q1 = [Link](qry);
int count = [Link]();
[Link]("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
[Link], [Link], st.tot_m
from StudentBean as st where st.tot_m >= :tm";
Query q1 = [Link](qry);
//setting values for marks
[Link]("tm", 98.0f);
int count = [Link]();
[Link]("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 = [Link]([Link]);
List results = [Link]();
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 = [Link]([Link]);
[Link]([Link]("salary", 2000));
List results = [Link]();
More Examples
Criteria cr = [Link]([Link]);
// To get records having salary more than 2000
[Link]([Link]("salary", 2000));
// To get records having salary less than 2000
[Link]([Link]("salary", 2000));
// To get records having fistName starting with zara
[Link]([Link]("firstName", "zara%"));
// Case sensitive form of the above restriction.
[Link]([Link]("firstName", "zara%"));
// To get records having salary in between 1000 and 2000
[Link]([Link]("salary", 1000, 2000));
// To check if the given property is null
[Link]([Link]("salary"));
// To check if the given property is not null
[Link]([Link]("salary"));
// To check if the given property is empty
[Link]([Link]("salary"));
// To check if the given property is not empty
[Link]([Link]("salary"));
Using AND OR operators
Criteria cr = [Link]([Link]);
Criterion salary = [Link]("salary", 2000);
Criterion name = [Link]("firstNname","zara%");
// To get records matching with OR condistions
LogicalExpression orExp = [Link](salary, name);
[Link]( orExp );
// To get records matching with AND condistions
LogicalExpression andExp = [Link](salary, name);
[Link]( andExp );
List results = [Link]();
Sorting the Results
The Criteria API provides
the [Link] 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 = [Link]([Link]);
// To get records having salary more than 2000
[Link]([Link]("salary", 2000));
// To sort records in descening order
[Link]([Link]("salary"));
// To sort records in ascending order
[Link]([Link]("salary"));
List results = [Link]();
Projections & Aggregations:
The Criteria API provides
the [Link] 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 = [Link]([Link]);
// To get total row count.
[Link]([Link]());
// To get average of a property.
[Link]([Link]("salary"));
// To get distinct count of a property.
[Link]([Link]("firstName"));
// To get maximum of a property.
[Link]([Link]("salary"));
// To get minimum of a property.
[Link]([Link]("salary"));
// To get sum of a property.
[Link]([Link]("salary"));
Fetching Few Columns
Criteria cr = [Link]([Link])
.setProjection([Link]()
.add([Link]("id"), "id")
.add([Link]("Name"), "Name"))
.setResultTransformer([Link](Us
[Link]));
List<User> list = [Link]();
Second Level Cache in Hibernate