Home » Java » java – CrudRepository Filter By One to Many Relation-Exceptionshub

java – CrudRepository Filter By One to Many Relation-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have two entity Customer and Order:

@Entity
public class Customer {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long id;
  .....
  @OneToMany(mappedBy="customer")
  private Set<Order> orders = new HashSet<Order>();
  .....
}

@Entity
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    ........
    @ManyToOne()
    private Customer;
    ........
}

In the CrudRepository I want to find all customers who have no orders.
How can I write the @Query? Or how can I write the method in CrudRepository Interface?

@Repository
public interface CustomerRepository extends CrudRepository<Customer, Long>{

  findBy ......

  @Query(".......")
  find.....

}

Thanks!

How to&Answers:

You need to use the empty keyword, that can be used with collection expressions (no need to join).

The JPQL query would be

select c from Customer c where c.orders is empty 

Answer:

To query data that’s not there you must use left join, something like this would do:

@Query("select c from Customer as c left join c.orders as orders where orders is null")