如何解决hibernate n+1问题OneToMany和ManyToOne
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<>();
而且我想避免休眠中的 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);
我对 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<>();
而且我想避免休眠中的 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);