| Author |
JPA - getSingleResult Error
|
nitin pai
Ranch Hand
Joined: May 30, 2006
Posts: 185
|
|
I am using Glassfish & Toplink with MySQL for implementing JPA. The project has a employee entity and a project entity with a many to many relation mapping. (emp_id and project_id are the primary keys respectively) This is the code in my session bean for fetching Employee along with eager fetching of related projects:
public Employee getEmployeeDetailsById(int id){ Query q = em.createQuery("select e from Employee e join fetch e.projects where e.empId=?1"); q.setParameter(1, id); Employee e = (Employee) q.getSingleResult(); return e; }
But when I try to access this method from my client, it gives out an error saying
When I run the query directly on MySQL it returns only a single row, then why this exception is thrown?
|
|
 |
Sergio Tridente
Ranch Hand
Joined: Mar 22, 2007
Posts: 329
|
|
This is because you are doing a LEFT JOIN FETCH in you query. Try doing this instead: You should get a sigle result then.
|
SCJP 1.4 (88%) - SCJP 5.0 Upgrade (93%) - SCWCD 1.4 (97%) - SCBCD 5.0 (98%)
|
 |
nitin pai
Ranch Hand
Joined: May 30, 2006
Posts: 185
|
|
Sergio, I actually want to do a JOIN FETCH query since my Employee entity has a collection of Project entities and I want them to be eagerly loaded when my Employee entity is fetched. But the query I mentioned above is giving the error. The query which you have given works fine but Project collection is not fetched. Can you explain why is this not the case when I use JOIN FETCH?
|
 |
Sergio Tridente
Ranch Hand
Joined: Mar 22, 2007
Posts: 329
|
|
Because it is doing a join (an outer join in fact). If you have more than one project related to that employee, you'll get more than one result. This is the SQL equivalent of what you are doing:
|
 |
tiago carneiro
Greenhorn
Joined: Jul 27, 2011
Posts: 1
|
|
In your query
public Employee getEmployeeDetailsById(int id){
Query q = em.createQuery("select e from Employee e join fetch e.projects where e.empId=?1");
q.setParameter(1, id);
Employee e = (Employee) q.getSingleResult();
return e;
}
you have to use DISTINCT, like this:
see the spec:
A fetch join has the same join semantics as the corresponding inner or outer join, except that the related objects specified on the right-hand side of the join operation are not returned in the query result or otherwise referenced in the query. Hence, for example, if magazine id 1 has five articles, the above query returns five references to the magazine 1 entity.
Regards,
Tiago
|
 |
 |
|
|
subject: JPA - getSingleResult Error
|
|
|