Reputation: 8118
Is there anyway to write a query in jpa that filters child entities?
I have this entity:
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(targetEntity = Flow.class)
private Flow flow;
}
Flow entity:
@Entity
public class Flow {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany(targetEntity = Step.class)
private List<Step> steps;
}
Now I would like to get the project and his flow but the steps in the flow should be filtered on a start and endtime property.
What I'm doing right now is find the project and then loop trough all the steps and filter the steps.
Like this:
List<Step> steps = project.getFlow().getSteps();
List<Step> filteredSteps = new ArrayList<>();
for (int i = 0; i < steps.size(); i++) {
Step step = steps.get(i);
if (step.getStartTime() == null || step.getEndTime() == null) {
break;
}
if (step.getStartTime().isAfter(start) && step.getEndTime().isBefore(end)) {
filteredSteps.add(step);
}
}
Step entity:
@Entity
public class Step {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private LocalDateTime startTime;
private LocalDateTime endTime;
}
I don't see how I can add a query in my project repository which is a crudrepository to filter the steps in a child entity.
Upvotes: 0
Views: 1407
Reputation: 27018
Function like this in your Repository should be enough.
findByFlow_Steps_StartTimeAfterAndFlow_Steps_EndTimeBefore(Date startTime, Date endTime);
Upvotes: 2