JPA2标准的API:选择...在(从那里选择)(JPA2 Criteria-API: select

2019-06-25 02:07发布

我有以下的数据库模型:

A
aId

AB
aId
bId

B
bId
status

在春天的数据规范,我想回到A的情况下,当B.status是“X”。 该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;
          }
        };
     }
}

Answer 1:

返回A,使用标准API的情况下,规格如下:

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


Answer 2:

有包括在以前的文章中一些很好的例子,解决你试图在这里实现什么: JPA-2-0-标准的API,子查询,在表达式 。



Answer 3:

我想你想选择“从AB实体B是提供状况的实体”:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery(A.class);
Root<AB> ab = cq.from(AB.class);
cq.select(ab.get("id").get("a"));
cq.where(cb.equal(ab.get("id").get("b.status"), status));


文章来源: JPA2 Criteria-API: select… in (select from where)