我尝试使用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();
如何设置where子句例如where =&#34; 45&#34;。 提前谢谢。
答案 0 :(得分:8)
使用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();
答案 1 :(得分:2)
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();
答案 2 :(得分:1)
jpa中最好,最简单的方法:
public interface YourEntityRepository extends JpaRepository<YourEntity, Serializable> {
Long countByAgeGreaterThan(Integer age);
}
答案 3 :(得分:0)
你可以使用Query参数, 示例:
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);
}
它对你有用吗?