Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jpa

ejb-3.0

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

like image 395
Jim Ward Avatar asked Jan 21 '10 16:01

Jim Ward


People also ask

What is createNativeQuery in JPA?

Imagine having a tool that can automatically detect JPA and Hibernate performance issues.

What is EntityManager used for?

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.

How do I run native query in EntityManager?

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.


2 Answers

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.

like image 199
ewernli Avatar answered Sep 21 '22 11:09

ewernli


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.

like image 23
Omar Al Kababji Avatar answered Sep 21 '22 11:09

Omar Al Kababji