繁体   English   中英

如何解决 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<>();

我想避免 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM