我正在将Java8与Hibernate5和JPA2一起使用。我想计算结果集中的行数。我有以下有效的代码,但是,我想知道是否有更有效的方法吗?我认为下面的代码首先查询整个结果集,并对行进行计数。
final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
CriteriaQuery<Rating> criteria = criteriaBuilder.createQuery(Rating.class);
Root<Rating> root = criteria.from(Rating.class);
ParameterExpression<Job> param = criteriaBuilder.parameter(Job.class);
TypedQuery<Rating> queryRating = entityManager.createQuery(criteria);
queryRating.setParameter(param, job);
int results = queryRating.getResultList().size();
有没有一种方法可以使SQL执行
count(*)
?更新
感谢下面的@chsdk,我有了一个修改后的代码:
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(Rating.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
问题
如何使用
where
参数设置Job
子句?更多信息:
+--------+ +------------+ +-----+
| rating | | rating_job | | job |
+--------+ +------------+ +-----+
| ID | | RAT_ID | | ID |
| | | JOB_ID | | |
+--------+ +------------+ +-----+
Rating.java
@ManyToOne(fetch=FetchType.EAGER)
@JoinTable
(
name="rating_job",
joinColumns={ @JoinColumn(name="RAT_ID", referencedColumnName="ID") },
inverseJoinColumns={ @JoinColumn(name="JOB_ID", referencedColumnName="ID") }
)
private Job job;
更新
感谢@chsdk,这是我的有效版本:
final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class);
Root<Rating> root = criteria.from(Rating.class);
ParameterExpression<Job> param = criteriaBuilder.parameter(Job.class);
criteria.select(criteriaBuilder.count(root)).where(criteriaBuilder.equal(root.get("job"), param));
TypedQuery<Long> queryRating = entityManager.createQuery(criteria);
queryRating.setParameter(param, job);
Long results = queryRating.getSingleResult();
return results;
最佳答案
在带有CriteriaQuery
的 JPA2 中,您可以这样操作:
final CriteriaBuilder criteriaBuilder = entityManagerFactory.getCriteriaBuilder();
CriteriaQuery<Long> criteria = qb.createQuery(Long.class);
Root<Country> root = criteria.from(Rating.class);
criteria.select(criteriaBuilder.count(root));
ParameterExpression<Job> param = criteriaBuilder.parameter(Job.class);
criteria.where(criteriaBuilder.equal(root.get("job"), param));
制作一个
CriteriaQuery<Long>
而不是CriteriaQuery<Rating>
,以便在计算criteria.from(Rating.class)
结果的行数时为您提供行数。编辑:
我编辑了答案代码,以包括对查询中给定参数
Job
的测试,同时尊重您的实体映射。然后,要执行查询,您将需要编写:
TypedQuery<Country> query = em.createQuery(criteria);
query.setParameter(param, yourJobObject);
Long resultsCount = query.getSingleResult();
请注意,您需要将
query.getSingleResult()
包装在try ..catch
块中,因为它可能会引发错误。推荐人:
请检查the answer here和此JPA Criteria API Queries tutorial以进一步阅读。
关于Java Hibernate计数行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43468272/