You should use the Long type. The count of entities matching your criteria in could exceed Integer.MAX (2147483647) in some scenarios with a large DB. Therefor, the return type is Long.MAX which is astronomical in size (9223372036854775807).
Does Projections.count("fieldName") always yield a Long?
-
09-10-2022 - |
質問
I am trying to make a Hibernate Criteria
query to get the count of rows from a table that match a certain criteria. Something like
SELECT COUNT(*) FROM MyTable WHERE field1 = <numVal> and field2 = 'strVal2'
Here is my criteria code
public static int getTransactionCount(Session session, int parentID) {
Criteria criteria = session.createCriteria(MyTable.class);
return (Integer) criteria.add(Restrictions.eq("parentID", parentID))
.add(Restrictions.eq("txnType", TransactionType.SOME_TYPE))
.setProjection(Projections.count("txnID")).uniqueResult();
}
I get
Caused by: java.lang.ClassCastException:
java.lang.Long cannot be cast to java.lang.Integer
at com.mydomain.MyClass.getTransactionCount(MyClass.java:123)
Is there something wrong with my criteria code or should I always expect a long from getting a count?
解決
他のヒント
Comming from JPA specs said:
The result of the function COUNT is a Long value representing the number of values in the group.
The result of the function AVG is a Double value representing the average of the group.
The result of the function SUM is a Long if the summed fields are Long and Double if the fields are Double
所属していません StackOverflow