简体   繁体   English

CrudRepository 按一对多关系过滤

[英]CrudRepository Filter By One to Many Relation

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.CrudRepository我想找到所有没有订单的客户。 How can I write the @Query?我该如何编写@Query? Or how can I write the method in CrudRepository Interface?或者如何在 CrudRepository 接口中编写方法?

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

  findBy ......

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

}

Thanks!谢谢!

要查询不存在的数据,您必须使用left join ,如下所示:

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

You need to use the empty keyword, that can be used with collection expressions (no need to join).您需要使用可与集合表达式一起使用的empty关键字(无需加入)。

The JPQL query would be JPQL 查询将是

select c from Customer c where c.orders is empty 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM