Hibernate - HQL to retrieve a collection from a OneToMany unidirectional relationship

I have a one-to-many unidirectional class as follows:

public class Order { @OneToMany(cascade = CascadeType.ALL) @JoinTable(name="order_item", joinColumns={@JoinColumn(name="order_id")}, inverseJoinColumns={@JoinColumn(name="item_id")}) public Set<Item> getItems() { return items; } } 

Getting the contents of this order is usually simple:

 List<Item> items = order.getItems(); 

But for some reason, I could somehow filter my results and get only a part of the collection of items, such as all items that exceed a certain price, below a certain stock, etc. in the fastest way (without returning then everything is then filtered afterwards). To do this, I would execute an HQL query to retrieve elements for a specific order and add a few more things to my where clause or to my query object.

Intuitively, I would like this behavior (which is completely wrong):

 SELECT jointable.ITEM from order_item as jointable inner join jointable.order where order = :order 

But, of course, this is wrong, since HQL works in terms of mapped objects, so I cannot use the connection table in the query. So what is the right way to do this?

Edit:

I found the answer to this question, I need the following query:

 Select o.items from Order o where o = ? 

This allows me to get a collection of items to order without using a bi-directional relationship. At the second stage of this question, I got confused, but how to filter the results of this collection, the simplest example is:

 Select o.items from Order o where o = ? order by o.items.somenumberfield asc 

What returns an illegal attempt to collect dereferencing since I can filter my items?

Edit:

The decision to sell tickets is really correct, I misunderstood the decision.

+8
java hibernate hql
source share
2 answers
 select item from Order order inner join order.items item where order = :order and ... 

HQL queries use entities and their associations. The fact that the association uses the join table or not does not matter for HQL: you move around the associations, and Hibernate performs the corresponding translation in SQL.

+6
source share

It looks like you want to map the other side of this relationship, i.e. do this bidirectional mapping.

Then you can use the order number in your HQL:

 from Item as item where item.amount > :amount and item.order.id = :orderId 

From the HQL documentation:

from Cat like a cat, where cat.mate.id = 69 The query is efficient and does not require table joins.

The fact that you are trying to execute this query indicates that the relationship between the line and its order is important!

+3
source share

All Articles