Search code examples
javahibernatecriteriaprojection

Hibernate Query By Example and Projections


To make it short: hibernate doesn't support projections and query by example? I found this post:

The code is this:

User usr = new User();
usr.setCity = 'TEST';
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Example.create(usr))

Like the other poster said, The generated sql keeps having a where class refering to just y0_= ? instead of this_.city.

I already tried several approaches, and searched the issue tracker but found nothing about this.

I even tried to use Projection alias and Transformers, but it does not work:

User usr = new User();
usr.setCity = 'TEST';
getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Example.create(usr)).setResultTransformer(Transformers.aliasToBean(User.class));

Has anyone used projections and query by example ?


Solution

  • Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).

    getCurrentSession().createCriteria(User.class)
    .setProjection( Projections.distinct( Projections.projectionList()
    .add( Projections.property("name"), "name")
    .add( Projections.property("city"), "city")))
    .add( Restrictions.eq("city", "TEST")))
    .setResultTransformer(Transformers.aliasToBean(User.class))
    .list();
    

    I've never used the alaistToBean, but I just read about it. You could also just loop over the results..

    List<Object> rows = criteria.list();
    for(Object r: rows){
      Object[] row = (Object[]) r;
      Type t = ((<Type>) row[0]);
    }
    

    If you have to you can manually populate User yourself that way.

    Its sort of hard to look into the issue without some more information to diagnose the issue.