arthur
arthur

Reputation: 3325

how to access a list of objects array as a result of a JPQL's query

Schema: each Employee may have many phone numbers and each phone number belongs to an Employee (a one-to-Many Relationship).

Using the following JPQL query: SELECT e, p FROM Employee e JOIN e.phones p,

How would you handle the resulting List<Object[]> from this query in your application code? In terms of accessing each employee and his/her phone number in the app. Code from that List<Object[]>? Using

em.createNamedQuery("..").getResultList().get(1)[]
// or
em.createNamedQuery("..").getResultList().get(2)[0]

results in error.

Upvotes: 1

Views: 4249

Answers (1)

Thomas
Thomas

Reputation: 88707

The problem most likely is that getResultList() returns a non generic List and thus you'd have to cast it to List<Object[]> first.

Assuming, your list has at least one entry this should work:

Employee e = (Employee)((List<Object[]>)em.createNamedQuery("..").getResultList()).get(0)[0];

Update:

Just for the reference: depending on the JPA version you use, you might get a List<Object> instead. In that case you could cast the value to Object[]:

Employee e = (Employee)((Object[])em.createNamedQuery("..").getResultList().get(0))[0];

Upvotes: 1

Related Questions