38

I'm creating a complex query with multiple tables and need to list the result. Usually, I'm using the EntityManager and map the result to the JPA-Representation:

UserEntity user = em.find(UserEntity.class, "5");

Then I can access all values as the user UserEntity class defines it. But how can I access the field-values returned from a native, multiple-table query? What I get is a List of Objects. That's fine so far, but what "is" that Object? Array? Map? Collection? ...

//simpleExample
Query query = em.createNativeQuery("SELECT u.name,s.something FROM user u, someTable s WHERE s.user_id = u.id");
List list = query.getResultList();

//do sth. with the list, for example access "something" for every result row.

I guess the answer is quite simple, but most examples out there just show the usage when directly casting to a targetClass.

PS: In the example I could use the class-mappings of course. But in my case someTable is not managed by JPA, and therefore I don't have the entity nor do I have a class-representation of it, and since I'm joining like 20 tables, I don't want to create all the classes just to access the values.

8 Answers 8

65

General rule is the following:

  • If select contains single expression and it's an entity, then result is that entity
  • If select contains single expression and it's a primitive, then result is that primitive
  • If select contains multiple expressions, then result is Object[] containing the corresponding primitives/entities

So, in your case list is a List<Object[]>.

3
  • 1
    Hi, this results to a WARNING message in build... is there a way not to get that warning message uses unchecked or unsafe operations? May 30, 2018 at 2:50
  • I mean aside from using @SuppressWarnings("unchecked") May 30, 2018 at 3:03
  • 1
    Using Jackson and Java 8 streams: query.getResultList().stream().map(objectMapper::convertValue).collect(Collectors.toList()); May 21, 2019 at 6:12
58

Since JPA 2.0 a TypedQuery can be used:

TypedQuery<SimpleEntity> q = 
        em.createQuery("select t from SimpleEntity t", SimpleEntity.class);

List<SimpleEntity> listOfSimpleEntities = q.getResultList();
for (SimpleEntity entity : listOfSimpleEntities) {
    // do something useful with entity;
}
1
  • TypedQuery<SimpleEntity> q = em.createQuery("select t from SimpleEntity t"); ;)
    – Gaspar
    Apr 29, 2020 at 12:43
13

If you need a more convenient way to access the results, it's possible to transform the result of an arbitrarily complex SQL query to a Java class with minimal hassle:

Query query = em.createNativeQuery("select 42 as age, 'Bob' as name from dual", 
        MyTest.class);
MyTest myTest = (MyTest) query.getResultList().get(0);
assertEquals("Bob", myTest.name);

The class needs to be declared an @Entity, which means you must ensure it has an unique @Id.

@Entity
class MyTest {
    @Id String name;
    int age;
}
9

The above query returns the list of Object[]. So if you want to get the u.name and s.something from the list then you need to iterate and cast that values for the corresponding classes.

5
  • 1
    So, i assume that list[x].object[0] is the first value (u.name) and list[x].object[1] is the second (s.something) - so no assoc access?
    – dognose
    Dec 4, 2012 at 11:07
  • If you printing just out object[i] and all primitives and date/time should be printed in their default format. Mar 5, 2015 at 23:42
  • @ MGPJ Can you ellaborate answer with an example
    – Reenu
    Jun 3, 2016 at 4:53
  • Hi, this results to WARNING message uses unchecked or unsafe operations... is there a way to avoid the warning message? May 30, 2018 at 2:57
  • I mean aside from using @SuppressWarnings("unchecked") May 30, 2018 at 3:03
3

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

0

Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.

    //simpleExample
    Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u,  someTable s WHERE s.user_id = u.id", 
NameSomething.class);
    List list = (List<NameSomething.class>) query.getResultList();

Entity class:

    @Entity
    public class NameSomething {

        @Id
        private String name;

        private String something;

        // getters/setters



        /**
         * Generic put method to map JPA native Query to this object.
         *
         * @param column
         * @param value
         */
        public void put(Object column, Object value) {
            if (((String) column).equals("name")) {
                setName(String) value);
            } else if (((String) column).equals("something")) {
                setSomething((String) value);
            }
        }
    }
0

What if you create a bean with all required properties and cast the result using Java 8+ streams?

Like this:

public class Something {

    private String name;
    private String something;

    // getters and setters
}

And then:

import javax.persistence.Query;

...

Query query = em.createNativeQuery("SELECT u.name,s.something FROM user u, someTable s WHERE s.user_id = u.id", Something.class);
List<?> list = query.getResultList();

return list
         .stream()
         .map(item -> item instanceof Something ? (Something) item : null)
         .collect(Collectors.toList());

That way, you don't need to return List<Object[]> nor hide the warning with @SuppressWarnings("unchecked")

Ps.:

1 - I know that this post is very old. But... I'm here in 2021, so others will be coming here too =)

2 - This is wrong or bad practice? Let me know :D

1
  • 1
    This will cause NullPointerException, because map doesn't allow returning a null
    – darw
    Sep 23, 2021 at 16:31
-1

You can also update your hibernate to a version greater than 5.4.30.final

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.