如何从具有ManyToMany关系的联接表中获取对象?春季+冬眠

时间:2019-03-15 22:10:47

标签: java hibernate spring-boot hql jointable

我有两个实体:

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

数据库中有三个表:customercouponcustomer_coupons,客户可以购买优惠券,并且在购买表customer_coupons之后保存customers_id和{{ 1}}(客户可以有很多优惠券,而优惠券可以有很多顾客)。

我需要某种方式通过coupons_id表中的customerIdcouponId获取客户的优惠券。我有界面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); } 。有人可以帮助我创建正确的查询吗?

1 个答案:

答案 0 :(得分:0)

从客户中选择优惠券c加入c.coupons优惠券,其中c.id =:customerId和coupon.id =:couponId

JB Nizet的答案

相关问题