Select non-entities with JPA?

java, jpa

Solution

Is it possible with JPA to retrieve a instances of a non-entity classes with native queries?

No. Native queries can return entities only (if you tell them to do so by passing the `resultClass` or a `resultSetMapping` to the `createNativeQuery` method; if you don't, you will get collections of raw data).

In JPQL, you can use constructor expressions (SELECT NEW...) whith a non-entity constructor. But this is not supported for native queries, you'll have to do it manually.

Problem

Is it possible with JPA to retrieve a instances of a non-entity classes with native queries? I have a non-entity class that wraps two entities: ``` class Wrap{ Entity1 ent1; Entity2 ent2 } @Entity class Entity1{ ... } @Entity class Entity2{ ... } ``` How can I do something like that? ``` Query q = entityManager.createNativeQuery("native select here"); List<Wrap> list = q.getResultList(); ```

Original source