且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Hibernate:具有多对多连接表的条件?

更新时间:2022-10-17 16:10:02

刚处理完这个问题。你在考虑表格,而不是对象。只需引用 tags.name ,然后让Hibernate处理其余部分:

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

如果你看到SQL Hibernate吐出来了,你会发现它使用了连接表。


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.

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.