JPA多对多关联下findAllByCustomersId仅返回一行数据问题
多对多关联查询仅返回一行数据的问题解决
问题根源
你的Coupon实体中@ManyToMany的@JoinTable配置错误,关联字段搞反了,导致JPA无法正确解析多对多关联关系,进而查询结果异常。
修正步骤
修正Coupon实体的关联配置
Coupon作为关联关系的一方,@JoinTable的joinColumns应该指向自身的外键(coupon_id),inverseJoinColumns指向关联实体Customer的外键(customer_id),修正后的代码如下:public class Coupon { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String title; private double price; @ManyToMany @JoinTable(name = "customers_vs_coupons", joinColumns = @JoinColumn(name = "coupon_id"), inverseJoinColumns = @JoinColumn(name = "customer_id")) @JsonIgnore private List<Customer> customers; }验证查询方法
修正配置后,原有的List<Coupon> findAllByCustomersId(int customersId)方法会正确生成SQL,关联customers_vs_coupons表通过customer_id匹配,返回该用户关联的所有优惠券。可选:手动指定查询语句
若想更明确控制查询逻辑,可在CouponRepository中添加@Query注解的方法:@Query("SELECT c FROM Coupon c JOIN c.customers cust WHERE cust.id = :customersId") List<Coupon> findAllByCustomerId(@Param("customersId") int customersId);
内容的提问来源于stack exchange,提问作者Tzah Zazon
相关产品推荐
相关产品推荐

