简体   繁体   中英

Filter child entity in jpa

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.

这样的功能在您的存储库中就足够了。

findByFlow_Steps_StartTimeAfterAndFlow_Steps_EndTimeBefore(Date startTime, Date endTime);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM