Question

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??

Was it helpful?

Solution

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]));

        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top