1

I have a complex Native Query. So using JPA 2.0 (with Hibernate implementation), I have declared a NamedNativeQuery

@NamedNativeQuery(name="latestStatusByUser",
            query=" with latest_behav_status as "
                    + " (select .......),"
                    + " latest_behav_avail as ("
                    + " .......) "
                    + " select ........"                        
                    + " from user "
                    + " left outer join latest_behav_status lbs .... "
                    + " left outer join...."

So In my code I call:

List<UserBehavior> rec = entityManager.createNamedQuery("latestStatusByUser").getResultList();

But, as Result, I get a List of Object instead of List of UserBehavior. Even if I specify the result class, I get Error as UserBehavior is a POJO and not an Entity.

Using named Query, I new that I can use :

 select new org.project.UserBehavior(user_i...) from

But How to do with a NativeQuery and with JPA2.0 (JPA2.1 come with a solution, using @ConstructorResult):

http://mariemjabloun.blogspot.com/2014/05/jpa-mapping-native-query-to-bean-pojo.html

So the Question is how to map the resultset into a Bean using JPA 2.0??

MariemJab
  • 689
  • 8
  • 14
  • 1
    See this answer on Stackoverflow: http://stackoverflow.com/questions/13012584/jpa-how-to-convert-a-native-query-result-set-to-pojo-class-collection It seems like what you want to achieve is not possible using JPA 2.0. Is making UserBehavior an `@Entity` no solution for you? You could still copy its data into a DTO or POJO after retrieving the results from the database. Maybe we need some more information on your context. – Jack May 08 '14 at 09:12

1 Answers1

0

It is not possible to make the POJO (User) an Entity. So to resolve this problem, I have manually mapped my returned List of Array of Object.

List<User> records = entityManager.createNamedQuery("latestStatusByUser").getResultList();
List<User> userRecords = new ArrayList<User>();
Iterator it = records.iterator( );

    while (it.hasNext( )) {
        Object[] result = (Object[])it.next(); // Iterating through array object 
         
        userRecords.add(new User(result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7]));

        }
Machavity
  • 30,841
  • 27
  • 92
  • 100
MariemJab
  • 689
  • 8
  • 14