其他分享
首页 > 其他分享> > spring – JPA2 Criteria-API:select … in(select from where)

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

作者:互联网

我有以下数据库模型:

A
aId

AB
aId
bId

B
bId
status

在Spring数据规范中,我想在B.status为’X’时返回A的实例.
JPQL代码如下:

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

这些是模型类:

@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;
}

如何在春季规范中的JPA标准?

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;
          }
        };
     }
}

解决方法:

使用Criteria API返回A实例的规范如下:

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);
          }
        };
     }
}

标签:criteria-api,spring,jpa-2-0,specifications
来源: https://codeday.me/bug/20191001/1838298.html