How to get parent entity by child's field? I use Specification
I have repository
ParentRepository extends JpaRepository<Parent, Long>, JpaSpecificationExecutor<Parent>{
}
And two clases:
class Parent{
@Id
long id;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = ID_CHILD)
Child child;
}
class Child{
@ID
long id;
@OneToOne(mappedBy = "child", cascade = CascadeType.ALL)
Parent parent;
Date date;
}
I need to get parent by field of child. Need Parent who has child with date between two dates.
I tried to write class ParentSpecification but don't understand how to get it done.
public class ParentSpecification {
private ParenSpecification() {
}
public static Specification<Parent> byChildName(Date one, Date two){
return (root, query, criteriaBuilder) -> {
??????????
return criteriaBuilder....
};
}
}
Following code may help you. Here find the parent by the child date. You may change according to your need.
public class ParentSpecification {
public static Specification<Parent> byChildDate(Date one, Date two){
return (root, query, criteriaBuilder) ->
criteriaBuilder.between(root.get("child").get("date"), one, two);
}
}