【问题标题】:Criteria API (Specification JPA) Join标准 API(规范 JPA)加入
【发布时间】:2020-11-06 18:12:52
【问题描述】:

这是我目前的模型

@Entity
public class A {

@Id
private Long id;

String name;

...

@Entity
public class B {

@Id
private Long id;

@ManyToOne()
@JoinColumn(name = "a_id")
private A a;

@ManyToOne()
@JoinColumn(name = "c_id")
private C c;

...

@Entity
public class C {

@Id
private Long id;

private String status;

我想要一个 A 类列表,其中 C 类的状态为“活动”使用 Criteria API 和显式 JOIN 作为下面的示例,IN

Subquery<B> subQB = query.subquery(B.class);
Root<B> rootB = subQB.from(B.class);
subQB.select(rootB.get("c").get("id"))
                      .where(builder.equal(rootB.get("c").get("status"), "ACTIVE"));        
predicates.add(root.get("id").in(subQB)); // root is class A

感谢您的帮助。

【问题讨论】:

  • “仅使用规范”是指“使用 Criteria API”
  • @Andreas 是的。我会解决这个问题。
  • 那么,你想重写现有的查询吗?还有,AB有关系吗?
  • @Smutje 是的,我想重写。不,只有 B 与 A 和 C 有关系。

标签: java sql criteria specifications criteria-api


【解决方案1】:

如果没有实际运行的数据库,它不应该类似于

CriteriaBuilder cb = em.getCriteriaBuilder();

// Because the result is "A"
CriteriaQuery<A> q = cb.createQuery(A.class);

// Start from B
Root<B> bRoot = q.from(B.class);

// Path from B to A, as local variable to increase readability
Path<A> aPath = bRoot.get("a");

// Path from B to C and to C's status, as local variable to increase readability
Path<C> cPath = bRoot.get("c");
Path<String> cStatusPath = cPath.get("status");

// SELECT A FROM B WHERE B.C.Status = "ACTIVE"
q.select(aPath)
  .where(cb.equal(cStatusPath, "ACTIVE"));

编辑:

显式连接应该看起来与第一个解决方案非常相似,所以

CriteriaBuilder cb = em.getCriteriaBuilder();

// Because the result is "A"
CriteriaQuery<A> q = cb.createQuery(A.class);

// Start from B
Root<B> bRoot = q.from(B.class);

// Path from B to A, as local variable to increase readability
Path<A> aPath = bRoot.get("a");

// Join from B to C and to C's status, as local variable to increase readability
Join<B, C> cJoin = bRoot.join("c");
Path<String> cStatusPath = cJoin.get("status");

// SELECT A FROM B WHERE B.C.Status = "ACTIVE"
q.select(aPath)
  .where(cb.equal(cStatusPath, "ACTIVE"));

【讨论】:

  • 任何想法使用显式加入?我正在使用 Spring Jpa 规范
猜你喜欢
  • 2018-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 2019-12-07
  • 1970-01-01
  • 2011-10-17
  • 2017-01-12
相关资源
最近更新 更多