select count(*) in H2 returning different from postgres

514 views
Skip to first unread message

Seb

unread,
Sep 3, 2009, 5:05:50 AM9/3/09
to H2 Database
Hi,
We are in a process of replacing postgres database with H2. We have a
Java project which uses Spring and Hibernate. We were proceeding well
until I got this problem

We use named queries that retrieve the number of transactions that
occured like (select count(*) from transaction_id). In the java code
we fetch the transaction numbers by the following code

List list = (List) getHibernateTemplate().findByNamedQueryAndNamedParam
("GetTransactionCount",
parameterName, paramArgs);
if (list.size() != 0) {
count = (Integer) list.get(0);
}

This is okay when we use postgres, but when we use H2, I get a
ClassCastException
Caused by: java.lang.ClassCastException: java.lang.Long cannot be
cast to java.lang.Integer


I am guessing the return that H2 database sends is of the type Long.
Is this how it is ? Is this a bug or is it how it is supposed to be in
H2.
I know I can typecast it to Long and the problem will be solved, but I
was just concerned as we are trying to make minimal changes to the
Java code.

Thomas Mueller

unread,
Sep 5, 2009, 12:03:15 PM9/5/09
to h2-da...@googlegroups.com
Hi,

> List list = (List) getHibernateTemplate().findByNamedQueryAndNamedParam
> ("GetTransactionCount",
>            parameterName, paramArgs);
> if (list.size() != 0) {
>              count = (Integer) list.get(0);
> }
>
> This is okay when we use postgres, but when we use H2, I get a
> ClassCastException
>        Caused by: java.lang.ClassCastException: java.lang.Long cannot be
> cast to java.lang.Integer
>
>
> I am guessing the return that H2 database sends is of the type Long.
> Is this how it is ? Is this a bug or is it how it is supposed to be in
> H2.

It's supposed to be a Long, but the documentation says 'Integer'. I
will change the documentation.

> I know I can typecast it to Long and the problem will be solved, but I
> was just concerned as we are trying to make minimal changes to the
> Java code.

Some databases return different data types depending on the actual
result (not sure about COUNT, but for SUM). Probably the most elegant
solution would be:

long count = ((Number) list.get(0)).longValue();

Regards,
Thomas

Reply all
Reply to author
Forward
0 new messages