Java 如何解决hibernate n+1问题
我对N+1休眠有问题。 我有以下实体:Java 如何解决hibernate n+1问题,java,hibernate,jpql,Java,Hibernate,Jpql,我对N+1休眠有问题。 我有以下实体: public class Coupon { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") private Long id; @Builder.Default @OneToMany(fetch = FetchType.LAZY, targetEntity = Coup
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<>();
我想避免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)
尝试使用以下查询:
@Queryselect c from优惠券c join fetch c.couponTypeList其中c.id=?1 可选getCouponLong couponId;
@查询从优惠券c中选择c join fetch c.couponTypeList t join fetch t.match,其中c.id=?1可选getCouponLong couponId;请注意,在尝试使用“join fetch”进行多个集合获取时,您可能会遇到MultipleBagFetchException。看这个。
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<>();
@Query("select c from Coupon c join fetch c.couponTypeList t join fetch t.match where c.id = ?1")
Optional<Coupon> getCoupon(Long couponId)