17

Consider the following two relations:

@Entity class Foo {
    @Id id;

    @ManyToMany
    @JoinTable(name = "ATag", 
         joinColumns = @JoinColumn(name = "foo_id"),
         inverseJoinColumns = @JoinColumn(name = "tag_id"))
    Set<Tag> tags;
}

@Entity class Tag {
    @Id Long id;
    String name;
}

There is no corresponding entity class for the join table ATag. Now, I want to get all Foo instances with Tag named 'tag1'. Is it possible using only Criteria?

A subquery may be helpful. However, I can't create DetachedCriteria for class ATag.class which doesn't existed.

1 Answer 1

33

Just dealt with this exact issue. You're thinking in tables, not objects. Just reference tags.name and let Hibernate take care of the rest:

Criteria crit = session.createCriteria(Foo.class);
crit.createAlias("tags", "tagsAlias");
crit.add(Restrictions.eq("tagsAlias.name", someValue);

If you watch the SQL Hibernate spits out, you'll see it uses the join table.

8
  • 1
    It is important to note about using the property of the object and not the object itself. Hibernate using Restrictions does not just use POJO defined primary key. Here the example uses the attribute name of the object tags. I lost of time trying to set the whole object instead of explicit say which property needs to be checked under the criteria predicate. Commented Jul 13, 2014 at 15:41
  • 3
    Why is it necessary to use an alias? Can't you simply use tags.name instead of tagsAlias.name?
    – sp00m
    Commented Mar 24, 2015 at 10:59
  • Creating an alias causes the inner join to happen automatically.
    – derrik
    Commented Aug 25, 2015 at 16:10
  • 1
    Works fine for one tag, but how to update this criteria to select Foo's which contains Tags named 'tag1' and 'tag2' on example?
    – Escander
    Commented Jul 18, 2016 at 4:33
  • @Escander just create a for loop and inside it add one Restriction at a time Commented Jul 25, 2018 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.