Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

spring - JPA2 Criteria-API: select... in (select from where)

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 when B.status is 'X'. The JPQL code is the following:

select a from A a where a in
     (select ab.id.a from AB ab where ab.id.b.status= :status)

These are the model classes:

@Entity
public class A {
     private Long aId;

     @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "id.a")
     private Set<AB> ab;
}

@Entity
public class B {
     private Long bId;
     private String Status;

     @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "id.b")
     private Set<AB> ab;
}

@Entity
public class AB {
     private ABPK id;
}

public class ABPK {
     @ManyToOne
     @JoinColumn(name="aId")
     private A a;

     @ManyToOne
     @JoinColumn(name="bId")
     private B b;
}

How would be the JPA Criteria in the Spring Specification?

public class ASpecifications {
     public static Specification<A> test(final String status) {
          return new Specification<Party>() {
          @Override
          public Predicate toPredicate(Root<A> a, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return null;
          }
        };
     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Specification that returns instances of A using Criteria API is the following:

public class ASpecifications {
     public static Specification<A> test(final String status) {
          return new Specification<Party>() {
          @Override
          public Predicate toPredicate(Root<A> a, CriteriaQuery<?> query, CriteriaBuilder cb) {
            Subquery<A> sq = query.subquery(A.class);
            Root<AB> ab = sq.from(AB.class);
            sq.select(ab.get(AB_.id).get(ABPK_.a));
            sq.where(cb.equal(ab.get(AB_.id).get(ABPK_.b).get(B_.status), status));

            Predicate p = cb.in(a).value(sq);
            return cb.and(p);
          }
        };
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...