Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: Criteria with many-to-many join table?

Consider 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 sub-query maybe helpful, however, I can't create DetachedCriteria for class ATag.class which isn't existed.

like image 344
Xiè Jìléi Avatar asked Jul 19 '11 09:07

Xiè Jìléi


People also ask

What should be done for many-to-many joins in hibernate?

In order to map a many-to-many association, we use the @ManyToMany, @JoinTable and @JoinColumn annotations. Let's have a closer look at them. The @ManyToMany annotation is used in both classes to create the many-to-many relationship between the entities.

How can we join multiple tables in hibernate criteria?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.

How many tables are created in many-to-many relationships hibernate?

Hibernate creates two tables in a many to many relationship.


1 Answers

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.

like image 137
atrain Avatar answered Sep 22 '22 05:09

atrain