简体   繁体   中英

How to resolve hibernate n+1 problem OneToMany and ManyToOne

I have problem with N+1 Hibernate. I have followings entities:

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<>();

And I want to avoid N+1 Problem in hibernate. How can I wrtie properly query in JPQL?

Solution:

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

Try to use the following query:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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