use of entityManager.createNativeQuery(query,foo.class)

Jim Ward picture Jim Ward · Jan 21, 2010 · Viewed 169.3k times · Source

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

Answer

ewernli picture ewernli · Jan 21, 2010

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.