如何从ManyToMany关系中获取连接表中的对象? Spring + Hibernate

问题描述 投票:0回答:1

我有两个实体:

@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_idcoupons_id(客户可以有很多优惠券和优惠券可以有很多客户)。

我需要以某种方式通过customerIdcouponIdcustomer_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。有人可以帮我创建正确的查询吗?

java hibernate spring-boot hql jointable
1个回答
0
投票

来自客户的SELECT优惠券c JOIN c.coupons优惠券WHERE c.id =:customerId AND coupon.id =:couponId

来自JB Nizet的回答

© www.soinside.com 2019 - 2024. All rights reserved.