0

I have 2 entities with the LAZY @ManyToMany relationship, which are mapped through guest_2_maintenance table: [order_id],[guest_id],[maintenance_id],[order_timestamp]

@Entity
public class Guest {
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "guests")
    private List<Maintenance> orderedMaintenances = new ArrayList<>();
}

@Entity
public class Maintenance {
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(
        name = "guest_2_maintenance",
        joinColumns = @JoinColumn(name = "maintenance_id"),
        inverseJoinColumns = @JoinColumn(name = "guest_id"))
    private List<Guest> guests = new ArrayList<>();
}

And I need to select List<Maintenance> of the guest through criteria. I may fetch the whole object and retrieve the List<Maintenance> through getter:

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Guest> cq = cb.createQuery(Guest.class);
    Root<Guest> root = cq.from(Guest.class);
    root.fetch("orderedMaintenances", JoinType.INNER);
    TypedQuery<Guest> query = entityManager.createQuery(cq
            .select(root)
            .where(cb.equal(root.get("id"), guestId))
            .distinct(true));
    Guest guest = query.getSingleResult();
    List<Maintenance> resultList = guest.getOrderedMaintenances();

But I want to have the ability for different sortings, so using sql instead of comparator for that is preferable, could you advise, how to select directly List<Maintenance> from query.getResultList()?

cognosce
  • 11
  • 4
  • check [here](https://stackoverflow.com/questions/8135612/jpa-criteria-for-many-to-many-relationship) – Pp88 Jul 28 '22 at 18:24
  • Does this answer your question? [jpa criteria for many to many relationship](https://stackoverflow.com/questions/8135612/jpa-criteria-for-many-to-many-relationship) – Pp88 Jul 29 '22 at 11:49
  • @Pp88 partly. There is the solution how to get the List<> with Join, meanwhile I was wondering about root.fetch possibilities to do that – cognosce Jul 29 '22 at 13:03

0 Answers0