简体   繁体   中英

How to use criterias for “many-to-many” relation?

Good afternoon. Learn Hibernate, it became necessary to write the following query using the criteria. 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). 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:

<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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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