0

I want to get all questions marked by tags "one" and "two" with Criteria API:

enter image description here

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Question.class);
    if (tags != null && tags.length > 0) {
        criteria.createAlias("tags", "t", JoinType.INNER_JOIN);
        Criterion[] criterions = new Criterion[tags.length];
        for (int i = 0; i < tags.length; i++) {
            criterions[i] = Restrictions.eq("t.name", tags[i]);
        }
        criteria.add(Restrictions.and(criterions));
    }
    return criteria.list();

When tags = ["one", "two"] nothing is returned, because, as I understand, hibernate firstly makes each row for each (question, tag) pair, then filters it, and only then grouping by Questions.

How can I fix this?

tags = ["one"] or tags = ["two"] works fine.

snieguu
  • 2,073
  • 2
  • 20
  • 39
sinedsem
  • 5,413
  • 7
  • 29
  • 46
  • I'm too lazy to use the ugly criteria API, so I'll give you a pseudo-JPQL query, and let you translate it if you really want to use Criteria. The principle is to check that one and two are both in the set of tags of the question. This assumes the question can't be tagged multiple times with the same tag: `select q from Question q where 2 = (select count(tag.id) from Question q2 where q2.id = q.id and tag.name in ('one', 'two'))` – JB Nizet Dec 24 '15 at 15:03
  • @xQbert disjuntion is perrrrfect, thanks a lot, couldn't google that question myself. – sinedsem Dec 24 '15 at 15:15

0 Answers0