hibernate本地查询,计数 [英] hibernate native query, count

查看:181
本文介绍了hibernate本地查询,计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何使用Hibernate计算行?

我想根据数据库中的条件计算记录数。

我尝试使用下一个查询

I want count number of records by criteria in database.
I try use next query

String queryString = "SELECT Count(*) FROM my_table";  
Query query = entityManager.createNativeQuery(queryString);  

但没有方法执行此查询查询
我知道,我可以使用

but there is no method to execute this Query query and get result.
I know, that I can count records using

String queryString = "SELECT * FROM my_table";  
Query query = entityManager.createNativeQuery(queryString); 
query.getResultList().size();  

所以问题是查询 Count(*)更多性能,如果 yes ,那么如何使用 Count(*)? >

so question, is query with Count(*) more performance, and if yes, then how can I execute query with Count(*)?

推荐答案

您可以通过调用 Query.getSingleResult()执行第一个查询,例如

You can execute your first query by calling Query.getSingleResult(), eg.

String queryString = "SELECT Count(*) FROM my_table";  
Query query = entityManager.createNativeQuery(queryString); 
System.out.println(query.getSingleResult());

如果要将计数分配给变量,您需要将其转换为正确的类型取决于DB,但很可能是长)。
第二个查询是非常低效的,因为Hibernate需要从DB检索整个表,分析它,然后对所有行计数。

If you want to assign the count to a variable you need to cast it to proper type (it can depend on DB but most likely it's Long). The second query is very inefficient because Hibernate needs to retrieve entire table from DB, analyze it and then count all rows.

这篇关于hibernate本地查询,计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆