2

I want to use Hibernate TypedQuery for a NativeQuery with Integer.class argument. Is it possible?

NativeQuery<Integer> query = session.createNativeQuery("select 1 from dual", Integer.class);
query.list(); //<--Error.  Caused by: org.hibernate.MappingException: Unknown entity: java.lang.Integer

or

query.getResultList(); //<--Error. Caused by: org.hibernate.MappingException: Unknown entity: java.lang.Integer

or

query.getSingleResult(); //<--Error. Caused by: org.hibernate.MappingException: Unknown entity: java.lang.Integer

I've found some examples on Web that suggest, this is theoretically possible.

see getTaskCount()

Update 1: I've updated the example.

Update 2: Add getSingleResult() example.

2 Answers 2

3

The resultClass parameter only accepts entity classes.

Also, when using native queries you are never guaranteed what what the return type for numbers will be, so using Integer or Long in a typecast will often blow-up on you when it's java.math.BigInteger.

What you need to do is:

Query query = em.createNativeQuery("select 1 from dual");  
Number nval = (Number) query.getSingleResult(); 
Integer val = nval == null ? null : nval.intValue();

Or for a list:

Query query = em.createNativeQuery("select 1 from dual");
List<Number> l = (List<Number>) query.getResultList();
for (Number nval : l) {
    Integer val = nval == null ? null : nval.intValue();
    // do stuff
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. But have you seen an example link? They are using Long.class as resultClass parameter.
Now I see they are using Query and not NativeQuery.
2

Second parameter of createNativeQuery() should be a mapped entity. Integer is not. So you have to do :

Query query = em.createNativeQuery("select 1 from dual");  
Integer val = (Integer) query.getSingleResult(); 

1 Comment

Sorry, but that's not quite true. I can use list() on query with only 1 result. I've updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.