【问题标题】:How to resolve hibernate n+1 problem OneToMany and ManyToOne如何解决休眠 n+1 问题 OneToMany 和 ManyToOne
【发布时间】:2021-04-26 02:14:33
【问题描述】:

我遇到了 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)

【问题讨论】:

    标签: java hibernate jpql


    【解决方案1】:

    尝试使用以下查询:

    @Query("select c from Coupon c join fetch c.couponTypeList where c.id = ?1")
    Optional<Coupon> getCoupon(Long couponId);
    

    【讨论】:

    • @Query("select c from Coupon c join fetch c.couponTypeList t join fetch t.match where c.id = ?1") 可选 getCoupon(Long couponId);
    • 当您尝试使用 `join fetch` 进行多个集合提取时,请不要遇到MultipleBagFetchException。看到这个question
    猜你喜欢
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    相关资源
    最近更新 更多