【问题标题】:JPA Predicate to get parent entity based on child entity countJPA Predicate 根据子实体计数获取父实体
【发布时间】:2017-12-01 08:57:55
【问题描述】:

我有以下实体结构:

@Entity
class ParentClass {
  @Id
  int id;
  @ManyToMany
  List<ChildClass> childAttribute;
}

@Entity
public class ChildClass {    
  @Id
  int id;    
}

我想编写一个谓词来获取父实体,其中名为 childAttribute 的属性的大小为“零”。 谢谢。

【问题讨论】:

标签: hibernate jpa criteria-api


【解决方案1】:

可以这样做:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ParentClass> cq = cb.createQuery(ParentClass.class);
Root<ParentClass> root = cq.from(ParentClass.class);
cq.select(root)
    .where(cb.isEmpty(root.get("childAttribute")));

TypedQuery<ParentClass> query = em.createQuery(cq);
List<ParentClass> result = query.getResultList();

等效的 JPQL 查询是:

SELECT p FROM ParentClass p where p.childAttribute IS EMPTY

更多详情请参考JPQL syntax

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多