I have the following database model:
A
aId
AB
aId
bId
B
bId
status
In a Spring data Specification, I want to return the instances of A wh
Select In - is an option but you could achieve same result with double join. And its easier to make such a jpa specification:
SELECT A.ID FROM A LEFT JOIN AB ON A.ID = AB.A_ID LEFT JOIN B ON AB.B_ID = B.ID WHERE B.STATUS = 'STATUS'
Method would look like this:
public static Specification findB(String input) {
return new Specification() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery> cq, CriteriaBuilder cb) {
Join AjoinAB = root.joinList(A_.AB_LIST,JoinType.LEFT);
Join ABjoinB = AjoinAB.join(AB_.B,JoinType.LEFT);
return cb.equal(ABjoinB.get(B_.NAME),input);
}
};
}
Or shorter
public static Specification findB(String input) {
return (Specification) (root, cq, cb) -> {
Join AjoinAB = root.joinList(A_.AB_LIST,JoinType.LEFT);
Join ABjoinB = AjoinAB.join(AB_.B,JoinType.LEFT);
return cb.equal(ABjoinB.get(B_.NAME),input);
};
}
I know it's been a long time since this question arose, but I came across it when I tried to do the same. This is my solution that works and I hope it helps someone.
Entities below
@Entity
public class A {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "a")
private List abList;
}
@Entity
public class B {
@Id
private Long id;
private String status;
@OneToMany(mappedBy = "b")
private List abList;
}
@Entity
public class AB {
@Id
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "a_id")
private A a;
@ManyToOne
@JoinColumn(name = "b_id")
private B b;
}