tags:

views:

1337

answers:

2

I would like to return a List of Integers from a

javax.persistence.EntityManager.createNativeQuery call

Why is the following incorrect?

entityManager.createNativeQuery("Select P.AppID From P", Integer.class);

specifically why do I get "...Unknown entity: java.lang.Integer"

Would I have to create an entity class that has a single field that is an Integer ?

Thanks

+2  A: 

What you do is called a projection. That's when you return only a scalar value that belongs to one entity. You can do this with JPA. See scalar value.

I think in this case, omitting the entity type altogether is possible:

   Query query = em.createNativeQuery(  "select id from users where username = ?");  
   query.setParameter(1, "lt");  
   BigDecimal val = (BigDecimal) query.getSingleResult(); 

Example taken from here.

ewernli
Yes, My oversight I didn't need the 2nd parameter. Still puzzled as to why it didn't work. I have to work that out.Thanks
Jim Ward
+1  A: 

That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the @Entity annotation on it).

for you you should do the following:

Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();

or if you want to use HQL you can do something like this:

Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();

Regards.

Omar Al Kababji
Thanks, that is very helpful.
Jim Ward
u are welcome ;)
Omar Al Kababji