gpt4 book ai didi

spring - JPA2 Criteria-API : select. .. in(从哪里选择)

转载 作者:行者123 更新时间:2023-12-04 05:44:30 26 4
gpt4 key购买 nike

我有以下数据库模型:

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

Spring 规范中的 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);
}
};
}
}

关于spring - JPA2 Criteria-API : select. .. in(从哪里选择),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10854334/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com