休眠本机查询,计数 [英] hibernate native query, count

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

问题描述

可能的重复:
我们如何使用 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);  

但是没有办法执行这个Query query并得到结果.
我知道,我可以使用

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,但很可能是 Long).第二个查询效率很低,因为 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.

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

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