如何从具有 ManyToMany 关系的 join table 中获取对象? Spring + 休眠

How can I get object from join table with ManyToMany relationship? Spring + Hibernate

我有两个实体:

@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;
}

数据库中有三个table:customercouponcustomer_coupons,客户可以购买优惠券,购买后tablecustomer_coupons 节省了 customers_idcoupons_id (客户可以有很多优惠券,优惠券可以有很多客户)。

我需要以某种方式从 customer_coupons table 获得 customerIdcouponId 客户的优惠券。我有接口 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 coupon FROM Customer c JOIN c.coupons coupon WHERE c.id = :customerId AND coupon.id = :couponId

JB Nizet 的回答