When to use Hibernate projections?
Asked Answered
T

4

50

I am a little confused about Hibernate's projections and criteria. When to use projections and when to use criteria?

Tourbillion answered 21/9, 2011 at 10:23 Comment(1)
Think of projections like columns/summary you would like to present on a projector(so keywords like min/max/avg/sum/count/etc... comes into picture) // Think of criteria like a subset of the raw data(rows), possibly to confirm that a projection is correct (so keywords like where/and/etc... comes into picture. // Your manager: How did you come with this projection? You: Here are the criteria boss.Iciness
C
96

They're not mutually exclusive, you can use both at the same time. Projections are generally used in the context of some Criteria.

To put it simple, Hibernate Projections are used in order to query only a subset of the attributes of an entity or group of entities you're querying with Criteria. You can also use Projections to specify distinct clauses and aggregate functions like max, sum and so on. It's like referring to which data you're fetching. Like modifying the select clause in an SQL query.

Hibernate Criteria are used to define conditions the data has to satisfy in order to be selected. It's like referring to how is the data you're fetching. Like modifiying the from and where clauses of an SQL query.

Note that this how and which is not strictly true, it's just an orientation aimed to aid the OP. You can change which data you're fetching with createCriteria(String associationPath) for instance.

I'd suggest to take a look at this article Hibernate: Criteria Queries in Depth

Centrist answered 21/9, 2011 at 10:33 Comment(2)
And it is useful to count() as -> return (Number) session.createCriteria("Book").setProjection(Projections.rowCount()).uniqueResult();Chesterton
Well-said, thank you! I appreciated the comparison to SQL. That helped it "click" for me, as I have a little more background there.Aspiration
S
6

Projections are used to execute aggregate operations and to get single column query,with Restrictions we can access a ROW but with PROJECTIONS we can access whole COLUMN

EX -

public static void main(String[] args) {
    SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
    Session session = factory.getCurrentSession();
    try {
        session.beginTransaction();
        Criteria c = session.createCriteria(Student.class);
        Projection p = Projections.property("lastName");
        List<String> students = c.setProjection(p).list();
        for(String s:students)
            System.out.println(s);
        session.getTransaction().commit();
        session.close();
    } finally {
        factory.close();
    }
}

In the above example i used projection call to ADD a projection property "name" to the criteria. It returns winchester winchester winchester winchester , which is the lastName COLUMN in the table.

Output =

Hibernate: select this_.last_name as y0_ from student this_ winchester winchester winchester winchester

Note - We can add only one projection, if we add more than 1 projection previous one will be overridden. if you want to add more than one projection you will nedd ProjectionList class

Orignal Table -

enter image description here

Sledge answered 10/2, 2018 at 7:47 Comment(0)
M
1

Hibernate projections are useful for

1)Fetching only certain columns of the table

2)Performing aggregations like count,sum,max,min,avg.

Fetching only the columns which are needed improves the performance of the query.

Examples of projection

Projections using DTO

Projection List example

Marlee answered 6/1, 2020 at 5:32 Comment(0)
G
-1

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()

Remember, 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 wont 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

Criteria crit = session.createCriteria(Products.class);
crit.setProjection(Projections.proparty("proName"));
List l=crit.list();
Iterator it=l.iterator();
while(it.hasNext())
{
    String s = (String)it.next();
    // ---- print -----
}

If we add multiple projections to criteria then the last projection added will be considered to execute see…

Criteria crit = session.createCriteria(Products.class);

Projection p1 = Projection.property("proName");
Projection p2 = Projection.property("price");

crit.setProjection(p1):
crit.setProjection(p2):
List l=crit.list();
Gottuard answered 22/11, 2013 at 12:25 Comment(4)
How does this answer the question?Arjan
link to original java4s.com/hibernate/…Ceil
Projection class does not have the property method.Thoron
Must be Projections instead of Projection. Mind the 's' at the endAn

© 2022 - 2024 — McMap. All rights reserved.