2

I am making an SQL query via JPA and getting a List of Object Arrays. I wish to map these Object Arrays into a bean.

For example, my query gives me the following output.

List<Object[]> list = // myWorkingJpaQuery;
// list is of length 2. 
// Each Object array always holds a Long in index 0, 
// a TimeStamp in index 1 and a String in index 2. 

Instead of reading these values and performing casting, I wish to map it to a class as follows:

class ExampleClass{
    //all these variables matches the aliases in myWorkingJpaQuery.
    Long id;
    TimeStamp ts;
    String name;
    // get set
}  

Tried to use the above class my changing the JPA methods return type and assigning it in the calling class as follows but it doesn't work.

List<ExampleClass> list = // myWorkingJpaQuery with List<ExampleClass> as return type;

Is there a way to do this? It is currently working fine if I stick to Object Array but just trying not to use Objects and castings. For reference, I am using Spring.

kang
  • 707
  • 4
  • 17
  • You're to do an **o**bject **r**elation **m**apping, let the ORM do that for you. https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/ – Ali Ben Zarrouk May 27 '19 at 22:58
  • See if this is what you are meaning: https://stackoverflow.com/questions/2355728/jpql-create-new-object-in-select-statement-avoid-or-embrace – Juan May 27 '19 at 23:08

2 Answers2

0

Does your ExampleClass have a constructor ? if yes you should be able to do the following :

List<ExampleClass> myList = new ArrayList<ExampleClass>();
List<Object[]> list = // myWorkingJpaQuery;
for (int i = 0; i < list.size(); i++) {
        ExampleClass obj = new ExampleClass(list.get(i)[0],list.get(i)[1],list.get(i)[2]);
        myList.add(obj);
    }

And your done

Kamèl Romdhani
  • 342
  • 1
  • 9
  • I get your point but not what I am looking for. I wish to map the result directly after performing the query. This introduces new logic to loop. There has to be a way to map. The link above seems promising. – kang May 27 '19 at 23:18
0

Assuming you're using the native query (otherwise, the ORM tool will do this for you automatically):

You might have a code like this:

 EntityManager em = ...
 Query q = em.createNativeQuery("SELECT ...");
 List<Object[]> results = q.getResultList();

In this case, you might consider passing an additional parameter to createNativeQuery method:

 Query q = em.createNativeQuery("SELECT...", ExampleClass.class);
 List<ExampleClass> results = q.getResultList();

For more complicated/customized Mappings consider using Result Set Mappings feature

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97