0

Let's say I have user and each user has list of orders:

Setters, getters, ids are skipped

@Entity
class Order {
    private int price;
}


@Entity
class User {
    @OneToMany
    @JoinColumn(..)
    private Set<Order> orders;
}

With java criteria API I want to create query to load all Users that have orders with price > 100 and fetch Orders with this price.

If I create query like

criteriaBuilder.greaterThan(root.join("orders").get("price"), 100);

I'll get right users but with all orders. Can I fetch only required orders?

Feedforward
  • 4,521
  • 4
  • 22
  • 34

1 Answers1

0

You can use detached query criteria approach:

DetachedCriteria maxQuery = DetachedCriteria.forClass(Order.class);
maxQuery.add(Restrictions.gt("price", 100));

and add the maxQuery to your original User.class query as follows:

userQuery.add(Property.forName("orders").eq(maxQuery));

For reference when to use detached criteria in hibernate?

Monkey D. Luffy
  • 301
  • 1
  • 11