简体   繁体   English

通过自定义条件具有多种获取策略(LAZY,EAGER)

[英]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 有两层可以控制数据的获取:

  1. At the level of entity class via fetch type and fetch mode在实体级别 class 通过获取类型和获取模式
  2. At the query level via the "join fetch" clause or using @EntityGraph在查询级别通过“join fetch”子句或使用@EntityGraph

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.

相关问题 远程案例中的懒惰/急切加载策略(JPA) - Lazy/Eager loading strategies in remoting cases (JPA) JPA Hibernate 根据条件将多个子实体的获取类型从 Lazy 更改为 Eager - JPA Hibernate Change Fetch type from Lazy To Eager for multiple child entities based on condition 渴望使用多个选择但不使用FetchType.EAGER注释进行提取 - Eager fetching with multiple selects but without FetchType.EAGER annotation 实体中具有多个ManyToOne关系的Hibernate Eager和Lazy加载 - Hibernate Eager and Lazy loading with multiple ManyToOne relationship in an Entity JPA,我怎么能有两个查询,一个使用惰性,一个使用渴望获取? - JPA, how can i have two queries, one use lazy and one use eager for fetching? 有人可以指出我关于JPA / Hibernate懒惰/急切获取的特别好资源吗? - Can someone point me to a particularly good resource on JPA/Hibernate lazy/eager fetching? 渴望查询中的惰性关系? - Eager query in a lazy relation? 渴望在 Spring 规范中获取 - Eager fetching in a Spring Specification CDI + JPA多个@OneToMany-LAZY / EAGER-LazyInitializationException或无法实例化多个包 - CDI + JPA Multiple @OneToMany - LAZY/EAGER - LazyInitializationException OR Cannot instantiate multiple bags JPA - 渴望 - 懒惰的最佳实践 - JPA - Eager - Lazy best practice
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM