4
Problem
How do I receive the amount of record from a database table?
public Integer quantidadeRegistros() {
try {
Query query = em.createQuery("SELECT COUNT(*) FROM Categoria cat");
return (Integer) query.getSingleResult();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Error
Caused by: java.lang.RuntimeException: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
at erp.dao.CategoriaDao.quantidadeRegistros(CategoriaDao.java:100)
at erp.dao.CategoriaDao$$FastClassBySpringCGLIB$$8d3c7f86.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at erp.dao.CategoriaDao$$EnhancerBySpringCGLIB$$252f3a07.quantidadeRegistros(<generated>)
at erp.service.CategoriaService.quantidadeRegistros(CategoriaService.java:95)
The same mistake happened.
– Thiago Gomes
Check the update I put in
– ℛɑƒæĿᴿᴹᴿ
Why did you have to cast for a Long guy?
– Thiago Gomes
Because the amount of records is returned in Long by default. There are cases where an Integer may not hold the amount of records in a table with billions of records.
– ℛɑƒæĿᴿᴹᴿ
This was defined in the pads of Enterprise Javabeans 3.0, more specifically in clause 4.8.4 that defines: COUNT Returns Long. Further information on the specification link (in English): https://download.oracle.com/otndocs/jcp/ejb-3_0-fr-eval-oth-JSpec/
– ℛɑƒæĿᴿᴹᴿ