0

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.

user1166635
  • 2,741
  • 6
  • 22
  • 32
  • See [another so answer](http://stackoverflow.com/questions/264339/querying-manytomany-relationship-with-hibernate-criteria). – Tapas Bose Mar 04 '12 at 12:39
  • These solutions use HQL, but I need solution which using Criteria objects. – user1166635 Mar 04 '12 at 12:45
  • Your ShopFruit entity is unnecessary if the join table doesn't contain anything other than foreign keys to the two other entities. Have you read the documentation? What have you tried? What don't you understand in this documentation? http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#querycriteria-associations – JB Nizet Mar 04 '12 at 17:03

1 Answers1

0

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.

Community
  • 1
  • 1
Roy
  • 43,878
  • 2
  • 26
  • 26