休眠多对多:查找包含类B的所有类A的标准 [英] Hibernate many-to-many: Criteria for looking up all class A which contains class B
问题描述
对于每个问题,您都有几个标签。与标签相同。
如果问题包含标签hibernate,我想要做的是获取所有问题(及其相应标签)。
我最多可以用多对多表中的SQLQuery来完成它,并返回问题ID列表。然后使用restrictions.in的标准并抓住所有问题。但它太笨拙了,我敢打赌有更好的方法去做,是吗?
基本上,您需要创建一个别名并使用别名来查询子集合,如下所示:
List questions = sess.createCriteria(Question.class)
.createAlias(Tags,t)
.add(Restrictions.eq(t.name,hibernate))
.list();
我假设您实际上没有代表bridge表的类标签表,否则你需要创建2个别名,例如:
List questions = sess.createCriteria(Question。 class)
.createAlias(QuestionTag,qt)
.createAlias(qt.Tags,t)
.add(Restrictions.eq(t.name ,hibernate))
.list();
您可以从文档中找到更多信息:
I have 2 classes which have many to many relationship. I take the 'Question' and 'Tag' as an example to make the case more understandable.
For each question, you have several tags. The same as for tag.
What I would like to do is to get all questions (and their corresponding tags) if the question contain a tag says "hibernate".
I can at most do it with a SQLQuery in the many-to-many table and return a list of the question ID. Then use a criteria with a restrictions.in and grab all questions. But it's too clumsy and I bet there is a better way of doing it, is there?
Essentially, you need to create an alias and use the alias to query the child collection like so:
List questions = sess.createCriteria(Question.class)
.createAlias("Tags", "t")
.add( Restrictions.eq("t.name", "hibernate") )
.list();
I'm assuming you don't actually have a class that represents the "bridge" table to the tags table in this scenario, otherwise you'd need to create 2 aliases eg:
List questions = sess.createCriteria(Question.class)
.createAlias("QuestionTag", "qt")
.createAlias("qt.Tags", "t")
.add( Restrictions.eq("t.name", "hibernate") )
.list();
You can find out more from the docs:
这篇关于休眠多对多:查找包含类B的所有类A的标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!