【问题标题】:Simple JPA 2 criteria query "where" condition简单的 JPA 2 条件查询“where”条件
【发布时间】:2012-05-21 19:48:16
【问题描述】:

我正在学习 jpa-hibernate 基础知识。

我有这个查询来获取所有用户:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery();
        cq.select(cq.from(Utente.class));
        return getEntityManager().createQuery(cq).getResultList();

现在我想通过一个名为“ghost”的布尔字段进行过滤,它等于 true(或 false,这取决于)。

翻译:

SELECT * FROM users WHERE ghost = 0;

我必须使用 cq.where() 吗?怎么样?

【问题讨论】:

    标签: jpa jpa-2.0 criteria


    【解决方案1】:

    是的,你必须使用cq.where()

    试试这样的:

    Root<Utente> utente = cq.from(Utente.class);
    boolean myCondition = true;    // or false
    Predicate predicate = cb.equal(utente.get(Utente_.ghost), myCondition);
    cq.where(predicate);
    

    我使用了应该自动生成的规范元模型类Utente_。这避免了在键入字段名称时出错的风险,并增强了类型安全性。否则你可以使用

    Predicate predicate = cb.equal(utente.get("ghost"), myCondition);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多