java 休眠本机查询,计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13049137/
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-10-31 11:19:30  来源:igfitidea点击:

hibernate native query, count

javasqlhibernatecount

提问by Ilya

Possible Duplicate:
How do we count rows using 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 queryand get result.
I know, that I can count records using

但是没有方法可以执行此操作Query query并获得结果。
我知道,我可以使用

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

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

所以问题是,查询是否具有Count(*)更高的性能,如果yes,那么我该如何执行查询Count(*)

回答by Adam Dyga

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

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

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

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.

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

回答by RobertG

Have you tried calling query.getSingleResult()?

您是否尝试过调用 query.getSingleResult()?