1

I want to find All the objects of class A (class A has a Many To Many Relationship with class B) , which have at least one Object of the Set of the Objects of Class B with a certain value in a field .

I had searched around the internet and for Documentation though i can take the way around ,creating a list of invoices that the Summary describes but I was curious if I will be able to write with pure Specification.

@ManyToMany(mappedBy = "A.name")
 public class A {
   private Set<B> b; 
 }

@JoinTable(name = "AB",
joinColumns = {@JoinColumn(name = "B_id", referencedColumnName = "id")},                 
inverseJoinColumns ={@JoinColumn(name= "A_id",referencedColumnName="id")})
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
 public class B
 {
     private Object certainField;
     private Set<A> a;
 }

 public static Specification<A> hasB(Set<B> b) {
     return (a, cq, cb) -> {

         //I want to find all the Objects<A> which have an Element B with 
        // CertainField.equals(aValue);
       //     I find it hard to understand the syntax and i find no clue how 
     // to 
    //     make it work. 

    };
}

EDIT: Finally I found out. Criteria Builder more or less is an abstraction of an query in db in Sql. Thus the asnwer is JOIN.

 public static Specification<A> hasB(Set<B> b) {
          return (a, cq, cb) -> {
        SetJoin<A,B> jointENTITY  = a.joinSet("B")
         return cb.equal(jointEntity.get("certainField"),certainValue));
      };      
 }

Also a very helpful answer is this one: JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Blue Owl
  • 11
  • 2
  • CriteriaAPI is a terrible thing for sure. How would you do it with JPQL or SQL? – Simon Martinelli Jun 06 '19 at 12:59
  • @Simon Martinelli I can and I did make my a way around the problem for time pressuring reasons ,but for consistency I would like to know for refactor/curiosity purposes. – Blue Owl Jun 06 '19 at 13:21
  • @SimonMartinelli if you are still interensted, i found some time to write a proper answer to the question . – Blue Owl Oct 01 '19 at 11:25

0 Answers0