我有两个实体:
@Entity
public class Customer {
@Id
@GeneratedValue
private int id;
@Column(nullable = false)
private String name;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Collection<Coupon> coupons;
}
@Entity
public class Coupon {
@Id
@GeneratedValue
private int id;
@Column(nullable = false)
private String title;
@ManyToMany(mappedBy = "coupons")
private Collection<Customer> customers;
}
数据库中有三个表:customer
,coupon
和customer_coupons
,客户可以购买优惠券,并且在购买表customer_coupons
之后保存customers_id
和{{ 1}}(客户可以有很多优惠券,而优惠券可以有很多顾客)。
我需要某种方式通过coupons_id
表中的customerId
和couponId
获取客户的优惠券。我有界面customer_coupons
:
CouponRepository
但是这个查询不起作用,我得到@Repository
public interface CouponRepository extends JpaRepository<Coupon, Integer> {
@Query("SELECT c FROM Coupon c WHERE c.id IN (SELECT coupons.id FROM customer_coupons WHERE coupons_id = ?1 AND customer_id = ?2)")
Coupon findCustomerCoupon(int couponId, int customerId);
}
。有人可以帮助我创建正确的查询吗?
答案 0 :(得分:0)
从客户中选择优惠券c加入c.coupons优惠券,其中c.id =:customerId和coupon.id =:couponId
JB Nizet的答案