Atul Sharma
Atul Sharma

Reputation: 10645

Spring Data JPA / Hibernate fetch child conditionally

I have 2 classes.

Parent :

public class Cart {
 private int id;

 @OneToMany(targetEntity = Items.class, cascade = CascadeType.ALL)
 @JoinColumn(name="cart_id")
 private List<Items> items;
}

Child :

public class Items {
 private int id;
 private int itemId;
 private Boolean isActive;
}

Now when i return Cart class, all items which are mapped by fk are getting returned which is perfect.

But, now i need to pull items where isActive is true.

Tried checking isActive in setter of cart class but dosen't seems to be working.

What should be the standard way to achieve this.

Upvotes: 0

Views: 634

Answers (2)

Robert Niestroj
Robert Niestroj

Reputation: 16131

Make the relationship bi-directional and query it from Child/ChildRepository.

public ChildRepository extends JpaRepository{
  List<Items> findByActiveTrue();
}

Querying it this way gives you much more flexibility than querying from the parent. Now you can filter, sort and paginate dynamically, when the need arises.

If the condition is static you could use @Where(clause = "isActive=true")

Upvotes: 1

Grim
Grim

Reputation: 1974

Use a JPQL or HQL like this:

List<Item> items = em.createQuery("SELECT i.* FROM Cart c LEFT JOIN c.items WHERE c.id=:cid", Item.class).setParameter("cid",cartId).getResultList();

Upvotes: 2

Related Questions