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?
连接表ATag没有对应的实体类。现在,我希望使用名为“tag1”的Tag获取所有Foo实例,是否可以仅使用Criteria?
A sub-query maybe helpful, however, I can't create DetachedCriteria for class ATag.class which isn't existed.
子查询可能有用,但是,我不能为不存在的类ATag.class创建DetachedCriteria。
1 个解决方案
#1
27
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:
刚刚处理了这个问题。你在想的是表,而不是对象。只需引用tags.name并让Hibernate处理其余的事情:
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.
如果您看到SQL Hibernate吐出,您会看到它使用连接表。
#1
27
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:
刚刚处理了这个问题。你在想的是表,而不是对象。只需引用tags.name并让Hibernate处理其余的事情:
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.
如果您看到SQL Hibernate吐出,您会看到它使用连接表。