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
Imagine having a tool that can automatically detect JPA and Hibernate performance issues.
In JPA, the EntityManager interface is used to allow applications to manage and search for entities in the relational database. The EntityManager is an API that manages the lifecycle of entity instances. An EntityManager object manages a set of entities that are defined by a persistence unit.
You can define a native ad-hoc query by calling the EntityManager's createNativeQuery method and providing the SQL statement as a parameter. Or you can use the @NamedNativeQuery annotation to define a named query that you can execute in the same way as JPQL's @NamedQuery.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With