Xdg
Xdg

Reputation: 1835

How to specify return types of columns in NativeQuery

How to specify return types of columns in NativeQuery? Now Query returns BigInteger but I want to map it to Long.

@PersistenceContext
private EntityManager entityManager;

Object[] o = (Object[]) entityManager.createNativeQuery("SELECT x FROM y WHERE id = :id").setParameter("id", id).getSingleResult();
(Long) o[0];

Leads to

Caused by: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

In Hibernate there is addScalar function but in javax.persistence there it is not.

Thanks.

Upvotes: 0

Views: 1896

Answers (2)

Andy Dufresne
Andy Dufresne

Reputation: 6180

There doesn't seem to be any solutions but this link seems to provide a workaround to this. For e.g.

    Query query = em.createNativeQuery("SELECT PHONE_ID FROM PHONE WHERE PHONE_NUMBER = '40101930'");

    ((SQLQuery)((HibernateQuery) query).getHibernateQuery()).addScalar("PHONE_ID", StandardBasicTypes.LONG);
    Long phoneId = (Long) query.getSingleResult();

Upvotes: 1

Neil Stockton
Neil Stockton

Reputation: 11531

If you don't specify a result class you will get the return type of the JDBC driver for that column, which can be different dependent on the datastore in use. This is a native (SQL) query so dependent totally on the JDBC driver (as opposed to the JPA implementation)

Upvotes: 1

Related Questions