Native query count does not return the same type in SQL Server and H2

2

Hello,

I have a native query that does a simple count of records in a table:

public Long contar() {
    String sql "SELECT count(*) FROM Order";
    Query query = query.createNativeQuery(sql);
    // return...
}

In the system, we use SQL Server in production and for the integration tests we use the H2 database.

However, Hibernate does not seem to have a default of the returned data type of the count native between these two banks. In H2, a BigInteger is returned and in the Sql Server a Integer is returned. In queries using JPQL, the returned type is always Long , independent of the database.

So, if I try H2:

return ((Integer) query.getSingleResult()).longValue();

I get:

  

java.lang.ClassCastException: java.math.BigInteger can not be cast to java.lang.Integer

If I try to use BigInteger , H2 accepts and the tests pass. But when trying this on Sql Server:

return ((BigInteger) query.getSingleResult()).longValue();

I get the error:

  

java.lang.ClassCastException: java.lang.Integer can not be cast to java.math.BigInteger

I tried to use Long:

return (Long) query.getSingleResult();

But I get the error (as expected):

  

java.lang.ClassCastException: java.lang.Integer can not be cast to java.lang.Long

So, what would be the correct way to convert the counter value to work in both databases?

    
asked by anonymous 07.08.2018 / 21:47

1 answer

0

I remembered that I had this problem in a software I worked on, instead of H2 using HsqlDB, and I consulted my former colleagues to remember the solution.

You can use Number and convert the result to Long :

return ((Number) query.getSingleResult()).longValue();
    
07.08.2018 / 21:53