在 Java 中使用 EntityManager 返回计数本机查询的结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39857168/
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-11-03 04:41:59 来源:igfitidea点击:
Returning result of count native query using EntityManager in Java?
提问by java123999
I have the following SQL Query :
我有以下 SQL Query :
SELECT COUNT(*) FROM DOG where ID = 'SampleId';
I am trying to write this in java
:
我正在尝试将其写入java
:
public int returnCountOfDogTable(String id){
String sql= "SELECT COUNT(*) FROM DOG WHERE ID =:id";
Query query = persistence.entityManager().createNativeQuery(sql);
query.setParameter("id", id);
List<Integer> resultList = query.getResultList();
int result = resultList.get(0);
return result;
}
However I get this exception:
但是我得到这个例外:
java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer
How can I solve this?
我该如何解决这个问题?
回答by Dherik
You can also use Number
and call intValue()
:
您还可以使用Number
和调用intValue()
:
Query query = entityManager.createNativeQuery("SELECT COUNT(*) FROM DOG WHERE ID =:id");
query.setParameter("id", 1);
int count = ((Number) query.getSingleResult()).intValue();
回答by Boris
Make sense to use Query#getSingleResultmethod:
使用Query#getSingleResult方法有意义:
Query query = entityManager.createNativeQuery("SELECT COUNT(*) FROM DOG WHERE ID =:id");
query.setParameter("id", 1);
int count = ((BigInteger) query.getSingleResult()).intValue();
回答by Shark
Simply try this:
试试这个:
public int returnCountOfDogTable(String id) {
//...
List<BigDecimal> resultList = query.getResultList();
BigDecimal result = resultList.get(0);
return result.toIntValue();
}