Reputation: 2102
I have entity Workflow which has @OneToMany relation with ValidationResults class. It's fetch Lazy but sometimes I would like to get all the Workflows and interate on them accessing the ValidationResults. In that moment I want jpa to get all the data eagerly not query each time I access ValidationResults. I use springDataJpa, How to do it, is there any way to do it with @Query ?
I try to achieve something like that but I don't know how
//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();
Here are my entities.
@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;}
...............
}
And ValidationResult class
@Entity
@Table(name = "validation_results")
public class ValidationResults {
...
@ManyToOne
@JoinColumn(name = "workflow_id", insertable = false, updatable = false)
private Workflow workflow;
....
}
Upvotes: 0
Views: 858
Reputation: 9786
The spring boot-ish way of doing this is by using the @EntityGraph as described in the documentation.
Upvotes: 1
Reputation: 720
If you don't want to create another query, just call .size() of your list
Upvotes: 0
Reputation: 508
You can use fetch join in order to do it on @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")
Upvotes: 1