简体   繁体   中英

JPA Hibernate Change Fetch type from Lazy To Eager for multiple child entities based on condition

Parent Entity

  • Product

    public class ProductEntity extends BaseEntity { private static final long serialVersionUID = 1L; @Id @Column(name = "id", nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "product_uuid", nullable = false) private String uuid; @Column(name = "sku", nullable = true) private Long sku; @Column(name = "name", nullable = false) private String name; @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true) private Set<ProductInfoEntity> infos; @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true) private Set<ProductTaxEntity> taxes; }

Child Entity

  • Info
  • Tax

Only few cases child entities required to fetch eagerly. Is there any way to change child entity fetch type from lazy to eager in either of the framework JPARepository/ CriteriaQuery/SQL

Tried almost every solution on stack overflow but every-time code will hit many queries to retrieve child entities

It's called N+1 problem in hibernate, You can solve it by using below methodologies...

-> By using JOIN FETCH
-> By using @EntityGraph and Projection

Because JOIN FETCH will make always single query for multiple tables using join internally.

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