[英]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.我有一个实体 class,它由多个外键约束组成,由 ManyToMany 等处理。
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.对于某些情况,我想将获取策略从例如从 EAGER 更改为 LAZY,反之亦然,因为对于某些读取操作,我不需要 EAGER 获取(想象一个 RESTful 服务,它只提供一小部分数据和不是所有的)但在大多数情况下我需要 EAGER 来代替。 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: JPA 有两层可以控制数据的获取:
I suggest you use FetchType.LAZY, by default for almost all associations.我建议您使用 FetchType.LAZY,几乎所有关联都默认使用。 And fetch them only when you need them via @EntityGraph.
并仅在需要时通过@EntityGraph 获取它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.