Pregunta

I'm working on a project that uses JPA (Hibernate), so almost all the queries are written in JPQL. But for a query I need to get down to the specific database type, so I've written a native query.

The project actually is tested with both MySQL and Oracle DBMS. My native query is a "SELECT 1 FROM [...]"; I then need to know if the result exists (easy) and if it's 1 (you could argue that's reduntant, I guess :-)).

In both cases I'm creating a javax.persistence.Query with createNativeQuery(String) and I run the query like this: Object r = q.getSingleResult(); (exceptions are taken care of already).
What I'm finding is that on MySQL r is a BigInteger, while in Oracle is of class BigDecimal.

I'm a nood at JDBC, is there any way (changing the query, the objects or the method calls I'm using) that I can be sure that my query will return the same datatype no matter what the database system is run against? Is this something that can be configured, that depends on jdbc, or is a driver-specific problem?

¿Fue útil?

Solución

Both BigInteger and BigDecimal are subclasses of Number. So, just cast to the common supertype and use it's methods to cast it to a primitive type such as int.

Number r = (Number) q.getSingleResult();
boolean isOne = (r.intValue() == 1);

Hibernate also has a very useful addScalar method. Take a look at Chapter 18 of its documentation for more information.

If you decide to use this solution, keep in mind that this means unwrapping your JPA layer and use vendor specific API:

Session session = entityManager.unwrap(Session.class);
Integer r = (Integer) session.createSQLQuery("SELECT 1 AS one FROM [...]")
   .addScalar("one", IntegerType.INSTANCE)
   .uniqueResult();

Finally, JPA has its own SqlResultSetMapping annotation. With it you can wrap your native results in a Entity. JPA Providers will do its best to cast each database column to their respective entity field type. Still, for scalar values it is too much overhead (I would go with the first solution).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top