Criteria for hibernation: look forward to the ManyToMany collection

My problem seems pretty simple to me, but I just can't find the answer that works. I have a Hibernate Entity that has an association of ManyToMany with another Entity, which by default is created dishonestly. I want to create a criterion that returns an Entity with a loaded ManyToMany association.

Here is the object in question (with the removal of unnecessary parts):

@Entity
public class Order {

  @ManyToMany
  private List<Item> items;

  @ManyToMany
  private List<Discount> discountEntries;

  ...

}

Here are my notable attempts and results:

Criteria criteria = getSession().createCriteria(Order.class)
                                .setFetchMode("items", FetchMode.SELECT)
                                .setFetchMode("discountEntries", FetchMode.SELECT);
criteria.list();

- lazily loads items

Criteria criteria = getSession().createCriteria(Order.class)
                                .setFetchMode("items", FetchMode.JOIN)
                                .setFetchMode("discountEntries", FetchMode.JOIN);
criteria.list();

- Unable to get multiple packages

Criteria criteria = getSession().createCriteria(Order.class)
                                .createAlias("items", "items", CriteriaSpecification.INNER_JOIN)
                                .setFetchMode("items", FetchMode.JOIN)
                                .createAlias("discountEntries", "discountEntries", CriteriaSpecification.INNER_JOIN)
                                .setFetchMode("discountEntries", FetchMode.JOIN);
criteria.list();

- returns an empty list

EDIT: Added another ManyToMany association, which seems to be part of the problem.

+3
source share
2

LAZY :

List list = criteria.list();
Hibernate.initialize(list);

, .

+2

: @ManyToMany(fetch = FetchType.EAGER)? ?

+2

Source: https://habr.com/ru/post/1727466/


All Articles