2023-01-29

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 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?



No comments:

Post a Comment