cladob
cladob

Reputation: 11

How to use Hibernate criteria aliasses in proiections?

I have following code:

Criteria c = getMySession()
            .createCriteria(Company.class, "company")
            .createAlias("company.employees", "employee")
            .add(Restrictions.eq("company.name", companyName))
            .add(Restrictions.eq("employee.workingHours", companyName))
            .setFirstResult(firstResult)
            .setMaxResults(maxResults)
            .setProjection(Property.forName("employee"))
            ;

A Company has a list of Employee entity

If I use

.setProjection(Property.forName("employee.name"))

the result is a list of Strings of the employees' names.

If I use

.setProjection(Property.forName("employee"))

I'm expecting a list of Employee entities. What I am getting is an error saing that "employee" is not a property of Company. How can I retrieve a list of Employee objects ?

Upvotes: 1

Views: 49

Answers (1)

StanislavL
StanislavL

Reputation: 57381

If you need Employee then build the query to return Employee initially.

        Criteria c = getMySession()
        .createCriteria(Employee.class, "employee")
        .createAlias("employee.company", "company")
        .add(Restrictions.eq("company.name", companyName))
        .add(Restrictions.eq("employee.workingHours", companyName))
        .setFirstResult(firstResult)
        .setMaxResults(maxResults)
        ;

Upvotes: 1

Related Questions