0

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 e.g. 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?

  • 1
    Mark it as lazy (for safety) and use an entity graph (fetch or load graphs) to define what you need for the specific use case involved. Many tutorials and questions already out there on this ( https://stackoverflow.com/a/31978349/496099 ) – Chris Jan 27 '23 at 15:15

1 Answers1

0

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.