简体   繁体   English

如何使用“多对多”关系标准?

[英]How to use criterias for “many-to-many” relation?

Good afternoon. 下午好。 Learn Hibernate, it became necessary to write the following query using the criteria. 学习Hibernate,有必要使用该标准编写以下查询。 There are two entities - a fruit shop and the type of communication - many to many. 有两个实体-水果店和通讯类型-多对多。 Accordingly, we have literally three tables (and the corresponding classes of Java): Fruit (id, name), Shop (id, name) and ShopFruit (shop_id, fruit_id). 因此,我们实际上有三个表(以及Java的相应类):Fruit(ID,名称),Shop(ID,名称)和ShopFruit(shop_id,fruit_id)。 So, as with the criterion to obtain a list of stores selling, say, a tangerine? 那么,与获取例如橘子的商店清单的标准一样? Thanks in advance. 提前致谢。

I think you can use an alias like so: 我认为您可以使用这样的别名:

List questions = session.createCriteria(Shop.class)
  .createAlias("Fruits", "f")
  .add(Restrictions.eq("f.name", "tangerine"))
  .list();

See also this question . 另请参阅此问题 However, I think you can also solve this with a set in your Hibernate mapping for Fruit: 但是,我认为您也可以在Hibernate映射中为Fruit设置一个集合来解决此问题:

<set name="stores" table="ShopFruit" cascade="all">
  <key column="fruit_id" />
  <many-to-many column="store_id" />
</set>

Extends your Fruit class with a stores set: 通过商店集扩展您的Fruit类:

class Fruit {
  ...
  Set<Store> stores;
  ...
}

If you than load the "tangerine" Fruit object from the database, the stores variable should have all the stores selling it. 如果您要从数据库中加载“橘子” Fruit对象,则stores变量应包含所有出售它的商店。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM