JPA-急切的ManyToOne按需

时间:2018-09-18 14:23:56

标签: java hibernate jpa

我有实体Workflow,它与ValidationResults类具有@OneToMany关系。它很懒惰,但有时我想获得所有工作流并通过它们访问ValidationResults。在那一刻,我希望jpa每次访问ValidationResults时都急切地获取所有数据而不查询。我使用springDataJpa,该怎么做,有什么方法可以使用@Query吗?

我试图实现类似的目标,但我不知道如何

   //here all the workflows has corresponding data eagerly
    List<Workflow> workflows = workflowService.getAllWorkflowsWithValidationResultsEagerly();

    //here validationResults ref is lazy, when I try to access it it does query
    List<Workflow> workflows = workflowService.getAllWorkflowsUsually();

这是我的实体。

@Entity
@Table(name = "workflow")
public class Workflow {

     ..............   

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "workflow", cascade = CascadeType.ALL)
    private Set<ValidationResults> validationResultsSet = new HashSet<>();

    public Set<ValidationResults> getValidationResultsSet(){return this.validationResultsSet;}
    ...............
}

和ValidationResult类

@Entity
@Table(name = "validation_results")
public class ValidationResults {
...
    @ManyToOne
    @JoinColumn(name = "workflow_id", insertable = false, updatable = false)
    private Workflow workflow;

 ....
}

3 个答案:

答案 0 :(得分:1)

您可以使用fetch join以便在@Query https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/fetch-join.html

上执行此操作
@Query("SELECT DISTINCT e FROM Employee e INNER JOIN FETCH e.tasks t")

答案 1 :(得分:1)

春季启动方式是通过使用@EntityGraph,如文档中所述。

答案 2 :(得分:0)

如果您不想创建其他查询,只需调用列表的.size()