How to use JOIN using Hibernate's session.createSQLQuery()

javauser71 picture javauser71 · Jan 14, 2011 · Viewed 13.2k times · Source

I have two Entity (tables) - Employee & Project. An Employee can have multiple Projects. Project table's CREATOR_ID field refers to Employee table's ID field. Employee entity does not maintain any reference for Project - but Project entity has a reference for Employee.

Using EntityManager following query works fine -

entityManager.createQuery(
    "select e from EmployeeDTO e, ProjectDTO p"
    + " where p.id = ?1 and p.creator.id=e.id");

But since I have the LAZY association relationship, I get error:

Could not initialize proxy - no Session

if I try to access Project info from Employee entity. This is expected and so I am using Hibernate's Session to create query as shown below.

Session session = HibernateUtil.getSessionFactory().openSession();
org.hibernate.Query q = session.createSQLQuery(
    "SELECT E FROM EMPLOYEE_TAB E, PROJECT_TAB P  WHERE P.ID = "
    + projectId + " AND P.CREATOR_ID = E.ID")
    .addEntity("EmployeeDTO ", EmployeeDTO.class)
    .addEntity("ProjectDTO", ProjectDTO.class);

But I get error like: "Column 'E' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification..."

Can anyone suggest what will be the right JOIN syntax for such case? If I use ("SELECT * FROM EMPLOYEE_TAB E, ........") - it gives other error:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.im.server.dto.EmployeeDTO

.

Thanks in advance.

Answer

axtavt picture axtavt · Jan 14, 2011

You don't need to use a native SQL query to prefetch ProjectDTOs when loading EmployeeDTO. Your original query can be rewritten in more elegant way as follows:

select e from EmployeeDTO e join e.projects p where p.id = ?1

Then you can add a join fetch clause in order to prefetch the projects:

select distinct e from EmployeeDTO e join e.projects p join fetch e.projects where p.id = ?1

See also: