简体   繁体   中英

Having multiple fetching strategies (LAZY, EAGER) by custom condition

I have one entity class, which consists of multiple foreign key constraints, which are handled by ManyToMany etc.

public class MyExampleClazz {
.......

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "secondClazzEntities", joinColumns = @JoinColumn(name = "id"),
        inverseJoinColumns = @JoinColumn(name = "id"))
List<MySecondClazz> secondClazz;
  
.....
}

For some cases, I would like to change the fetching strategy from eg from EAGER to LAZY and vice versa, because for some read operations, I don't need EAGER fetching (imagine a RESTful service, which offers only some small portion of data and not everything) but in most cases I need EAGER instead. One option could be introduce an entity (for same table) but different annotation, but it would duplicate code and effort in regards of maintenance.

Are there other ways present, to achive the same result by doing less?

There're two layers where you can control data fetching in JPA:

  1. At the level of entity class via fetch type and fetch mode
  2. At the query level via the "join fetch" clause or using @EntityGraph

I suggest you use FetchType.LAZY, by default for almost all associations. And fetch them only when you need them via @EntityGraph.

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