hibernatehibernate-criteriadetachedcriteria

Extra entities in search result when Hibernate Criteria used


I have class Event with field linkedRooms:

public class Event
{
    Set<LinkedRoom> linkedRooms;
    ...
}

Class LinkedRoom has field sourceKey:

public class LinkedRoom
{
    Long sourceKey;
    ...
}

I need to search all events that have all linked rooms with not null sourceKey field.

I used Hibernate Criteria in DAO:

public List<Event> search(EventSearchCriteria searchCriteria)
{
    Criteria criteria = getCurrentSession().createCriteria(clazz);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    criteria.createAlias("linkedRooms", "lr");
    criteria.add(Restrictions.isNotNull("lr.sourceKey"));
    return criteria.list();
}

But I get events that have at least one linked room with not null sourceKey. Please help me, what I doing wrong?


Solution

  • Here is solution for my problem:

    DetachedCriteria todaysBook = DetachedCriteria.forClass(Event.class, "be")
                        .createAlias("be.linkedRooms", "belrs")
                        .add(Restrictions.isNull("belrs.sourceKey"))
                        .setProjection(Property.forName("id"));
                criteria.add(Property.forName("id").notIn(todaysBook));