Search code examples
hibernatehql

Wrong result using hql 'or'


I don't know what am I missing here. I'm trying to run a query as follow:

String query = "select e from Event e where (eventType.operation='LIKE' and relatedPost.creatorPerson.personId=:person1Id)"
                + " or (eventEntity.relatedEntity='PERSON' and eventType.operation='FOLLOW' and relatedPerson.personId=:personId)"
                + " order by creationDate desc";
beginTx();
Query q = session.createQuery(query);
q.setInteger("personId", id1);
q.setInteger("personId1", id2);
List<Event> events = q.list();
commitTx();

When I query each side of 'or' separately, I get correct results. but when running whole above query, I just get result of left side of 'or'.

Any helps please?


Solution

  • Okay, now I'm quite sure about my comments...

    The problem is that relatedPost.creatorPerson will result in an inner join (actually even two) and therefor you will not get any results for the right part of the or when relatedPost or relatedPost.creatorPerson is null. You should get a result if you explicitly specify some left joins:

    select e from Event e 
    left join e.relatedPost as rp 
    left join rp.creatorPerson as cp
    where (eventType.operation='LIKE' and cp.personId=:person1Id) 
    or (eventEntity.relatedEntity='PERSON' and eventType.operation='FOLLOW' and relatedPerson.personId=:personId) order by creationDate desc