[英]How to resolve hibernate n+1 problem OneToMany and ManyToOne
我對 N+1 Hibernate 有問題。 我有以下實體:
public class Coupon {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Builder.Default
@OneToMany(fetch = FetchType.LAZY,
targetEntity = CouponType.class,
cascade = CascadeType.ALL,
mappedBy = "coupon")
private List<CouponType> couponTypeList = new ArrayList<>();
public class CouponType {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private Match match;
@ManyToOne
private Coupon coupon;
public class Match {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Builder.Default
@OneToMany(fetch = FetchType.LAZY,
targetEntity = CouponType.class,
mappedBy = "match")
private List<CouponType> couponTypeList = new ArrayList<>();
我想避免 hibernate 中的 N+1 問題。 如何在 JPQL 中正確查詢?
解決方案:
@Query("select c from Coupon c join fetch c.couponTypeList t join fetch t.match where c.id = ?1")
Optional<Coupon> getCoupon(Long couponId)
嘗試使用以下查詢:
@Query("select c from Coupon c join fetch c.couponTypeList where c.id = ?1")
Optional<Coupon> getCoupon(Long couponId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.