Reputation: 156
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)
Upvotes: 1
Views: 243
Reputation: 13041
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);
Upvotes: 1