how to map query result to string array in java

select id,name,salary,city,state,country from employee where name like '%a%';

I need to map above query result to String array, position 0 always id, position 1 always name …… position 5 always country.

Using JPA or MyBatis is there a way we can dynamically map the select query values into fixed position string array ?

Leave a Reply

2 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

I’ve never personally used JPA, but – after reading through it a bit – believe this should be correct.

TypedQuery<Object[]> query = entityManager.createQuery(
  "SELECT id,name,salary,city,state,country FROM employee WHERE name LIKE '%a%'", Object[].class);
List<Object[]> results = query.getResultList();

where (Integer) results.get(index)[0] = id, (String) results.get(index)[1] = name, etc.

You can change Object[] to String[] if you would like an array of Strings.


Why do you want to use String array?

It is better to use an object list instead. It will be easier to get city of an employee using employee.getCity() versus array[3].

It makes for more readable code as well.

To use an object list, you need to create a model for your employee and annotate with @Entity and create a repository for that entity. JPA documentation should help do this easily