Java 如何使用JPA计算行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28211806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:47:56  来源:igfitidea点击:

How to count number of rows using JPA?

javahibernatejpa

提问by Harun ERGUL

I try to count number of rows using JPA.I want to use where clause however I can't.

我尝试使用 JPA 计算行数。我想使用 where 子句,但我不能。

CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where();  //how to write where clause 
return entityManager.createQuery(cq).getSingleResult();

How can I set where clause forexample where age="45". Thanks in advance.

如何设置 where 子句,例如 where age="45"。提前致谢。

采纳答案by Buhake Sindi

Use ParameterExpression. Note: Untested.

使用ParameterExpression. 注意:未经测试

CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
ParameterExpression<Integer> p = qb.parameter(Integer.class);
q.where(qb.eq(c.get("age"), 45));
return entityManager.createQuery(cq).getSingleResult();

Reference.

参考

回答by RichardK

EntityManagerFactory emf =
                    Persistence.createEntityManagerFactory("your table name");
            EntityManager em = emf.createEntityManager();


            // JPA Query Language is executed on your entities (Java Classess), not on your database tables;

            Query query = em.createQuery("SELECT count(*) FROM your Classname WHERE ... etc");
            long count = (long) query.getSingleResult();

回答by TinyOS

you can use the Query parameter, Example :

您可以使用查询参数,例如:

StringBuilder strQuery ;
    strQuery= new StringBuilder();
    try {
        strQuery.append("FROM SSS s where s.age:age");
        Query query = this.getEntityManager().createQuery(
                strQuery.toString());
        query.setParameter("age", 45);
    } catch (Exception e) {
        LOGGER.info("Erreur", e);
    }

it's useful for you?

对你有用吗?

回答by jdominus

The best and simple way in jpa :

jpa 中最好和最简单的方法:

public interface YourEntityRepository extends JpaRepository<YourEntity, Serializable> {

Long countByAgeGreaterThan(Integer age);

}