In criteria, we are able to load
complete object.
For loading the partial objects
while working with criteria, the projections concept is introduced in hibernate
3.0 and mainly we can do the following 2 operations using the projection
·
We can load partial object from the
database
·
We can find the Result of Aggregate
functions
Projection is an Interface given in “org.hibernate.criterion” package,
Projections is an class given in same package, actually Projection
is an interface, and Projections is an class and is a factory for producing
projection objects.
In Projections class, we have all static
methods and each method of this class returns Projection interface object.
If we want to add a Projection object
to Criteria then we need to call a method setProjection ()
Note: - While adding projection object to criteria, it is possible
to add one object at a time. It means if we add 2nd projection object
then this 2nd one will overrides the first one (first one won’t be work), so at
a time we can only one projection object to criteria object.
Using criteria, if we want to load
partial object from the database, then we need to create a projection object
for property that is to be loaded from the database.
public class
ProjectionExample {
public static void
main(String[] args) {
Session sess = null;
try {
SessionFactory
sfact = new Configuration().configure().buildSessionFactory();
sess = sfact.openSession();
Criteria
crit = sess.createCriteria(Product.class);
ProjectionList
proList = Projections.projectionList();
proList.add(Projections.property("name"));
proList.add(Projections.property("price"));
crit.setProjection(proList);
List
list = crit.list();
Iterator
it = list.iterator();
if (!it.hasNext())
{
System.out.println("No
any data!");
}
else {
while (it.hasNext())
{
Object[]
row = (Object[]) it.next();
for (int i =
0; i < row.length; i++) {
System.out.print(row[i] + " ");
}
System.out.println();
}
}
System.out.println();
crit.setProjection(Projections.rowCount());
List
result = crit.list();
System.out.println("No.
of rows: " + result);
crit.setProjection(Projections.distinct(Projections.countDistinct("name")));
List
distList = crit.list();
System.out.println("Distinct
Count: " + distList);
proList =
Projections.projectionList();
proList.add(Projections.sum("price"));
crit.setProjection(proList);
List
sumResult = crit.list();
System.out.println("Total
price Amount: " + sumResult);
sess.close();
} catch
(Exception e) {
System.out.println(e.getMessage());
}
}
}
O/P:-
Hibernate: select
this_.name as y0_, this_.price as y1_ from Product this_
Computer 23000.0
Mobile 15000.0
Laptop 200.0
Keyboard 1500.0
PenDrive 200.0
HardDisk 2500.0
Computer 100.0
Hibernate: select
count(*) as y0_ from Product this_
No. of rows: [7]
Hibernate: select
distinct count(distinct this_.name) as y0_ from Product this_
Distinct
Count: [6]
Hibernate: select
sum(this_.price) as y0_ from Product this_
Total price Amount: [42500.0]
0 comments: