我有以下SQL Query :
SELECT COUNT(*) FROM DOG where ID = 'SampleId';
我想在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;
}
但是我得到了这个例外:
java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer
我该如何解决这个问题?
答案 0 :(得分:7)
使用 Query#getSingleResult 方法:
Query query = entityManager.createNativeQuery("SELECT COUNT(*) FROM DOG WHERE ID =:id");
query.setParameter("id", 1);
int count = ((BigInteger) query.getSingleResult()).intValue();
答案 1 :(得分:3)
试试这个:
public int returnCountOfDogTable(String id) {
//...
List<BigDecimal> resultList = query.getResultList();
BigDecimal result = resultList.get(0);
return result.toIntValue();
}
答案 2 :(得分:2)
您还可以使用Number
并致电intValue()
:
Query query = entityManager.createNativeQuery("SELECT COUNT(*) FROM DOG WHERE ID =:id");
query.setParameter("id", 1);
int count = ((Number) query.getSingleResult()).intValue();