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.
Hibernate JPA implementation (Entity Manager) return null when you call query. getResultList() with no result. As pointed out by some users, it seems that a newest version of Hibernate returns an empty list instead. An empty list is returned in Eclipselink as well when no results are found.
getResultList() Execute a SELECT query and return the query results as an untyped List. java.lang.Object. getSingleResult() Execute a SELECT query that returns a single untyped result.
There is no standard way to get JPA to return a map.
JPQL syntax is very similar to the syntax of SQL. Having SQL like syntax is an advantage because SQL is a simple structured query language and many developers are using it in applications. SQL works directly against relational database tables, records and fields, whereas JPQL works with Java classes and instances.
General rule is the following:
select
contains single expression and it's an entity, then result is that entityselect
contains single expression and it's a primitive, then result is that primitiveselect
contains multiple expressions, then result is Object[]
containing the corresponding primitives/entitiesSo, in your case list
is a List<Object[]>
.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With