0

I have the problem with Hibernate criteria. I need get list of Company by some dynamic conditions and also by condition on Empoyee field (LAZY field). I created Criteria like this:

Criteria criteria = session.createCriteria(Company.class);

criteria.createAlias("employee", "employee");
criteria.add(Restrictions.eq("employee.someFieldForWhere", "text"));

criteria.list();

For add condition on Employee field I must add alias (in my case I added alias with same name 'employee').

But in this case I get incorrect and illegal SQL query - in this case Hibernate try to select all fields from alias:

    select
        this_.id as id1_0_1_,
        this_.employee_id as employee2_0_1_,
        employee1_.id as id1_1_0_,
        employee1_.someBigField as someBigF2_1_0_,
        employee1_.someFieldForWhere as someFiel3_1_0_ 
    from
        Company this_ 
    inner join
        Employee employee1_ 
            on this_.employee_id=employee1_.id 
    where
        employee1_.someFieldForWhere=?

It is not unacceptable, cause table Employee consists many fileds and I do not need load it in my request (in my example it loads id, someFieldForWhere and someBigField ).

So the question - How create criteria with condions on subentities, without selection fields of this subentities?

I need something like this:

        select
            this_.id as id1_0_1_,
            this_.employee_id as employee2_0_1_,
        from
            Company this_ 
        inner join
            Employee employee1_ 
                on this_.employee_id=employee1_.id 
        where
            employee1_.someFieldForWhere=?

The Project for play, with full sources - https://github.com/Akvel/criteriaTest

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135
Akvel
  • 924
  • 1
  • 15
  • 32

1 Answers1

0

You can specify the fields to select by setting the projections on your criteria

    Criteria criteria = session.createCriteria(Company.class);

    criteria.createAlias("employee", "employee");
    criteria.add(Restrictions.eq("employee.someFieldForWhere", "text"));

    ProjectionList projections = Projections.projectionList();
    // just the root id
    projections.add(Projections.id());
    // the associated entity id
    projections.add(Projections.property("employee.id");

    criteria.setProjections(projections);

    criteria.list();

See Hibernate docs

carbontax
  • 2,164
  • 23
  • 37
  • Already tried this way, in this case I will need add to projection all eager fields of root-entity everytime when fields is changing. In this case the problem is that you can not set to projection root-entity or some alias. – Akvel May 28 '14 at 06:25