【问题标题】:Spring Data/SQL Query to find all matches by collectionSpring Data/SQL Query 按集合查找所有匹配项
【发布时间】:2021-10-10 08:51:02
【问题描述】:

您能否建议如何在 Spring Data JPA 存储库中编写查询?情况如下: 我有 2 个实体:具有“OneToMany”关系的客户和产品 - 意味着一个客户可能有许多产品。在代码中,看起来 Customer 实体有 Set products 并且 Product 有对 Customer 客户的引用,非常简单。如果我从 DB JSON 中检索 Customer,将如下所示: {"id":10, "name":'John Smith',"personalCode":12345678,"products":[ {"id":15,"type":"productType1"}, {"id":20,"type":"productType2"}] }

问题是如何向数据库写入查询以查找其产品与通过产品集合匹配的所有客户?例如,我想查找拥有 type1 和 type2 产品的所有客户。谢谢!

@Entity
@Table(name = "customer")
public class Customer {

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

private String name;

private int age;

private String personalCode;

@Enumerated(EnumType.STRING)
private Country country;

private String internetBankUserId;

@Enumerated(EnumType.STRING)
private CustomerType type;

@JsonManagedReference
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
@SortNatural
private SortedSet<Product> products = new TreeSet<>();

@Entity
@Table(name = "product")
public class Product implements Comparable<Product>{

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

@Enumerated(EnumType.STRING)
private ProductType type;

@JsonBackReference
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "customer_id")
private Customer customer;

【问题讨论】:

标签: java sql spring spring-data-jpa


【解决方案1】:

这个解决方案对我有用:

@Query("SELECT c FROM Customer c join  c.products p where p.type in :products 
       and SIZE(c.products) >= :count")
Set<Customer> findAllByProductType (@Param("products")Set<ProductType> products,
                                    @Param("count") Integer count );

【讨论】:

    猜你喜欢
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 2021-09-05
    • 2021-10-17
    相关资源
    最近更新 更多