我有两个实体:
@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
和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);
}
但这一个查询不起作用,我得到QuerySyntaxException: customer_coupons is not mapped
。有人可以帮我创建正确的查询吗?
来自客户的SELECT优惠券c JOIN c.coupons优惠券WHERE c.id =:customerId AND coupon.id =:couponId
来自JB Nizet的回答