Search code examples
hibernatejpajpql

Is there an JPQL null safe expression


In the following JPQL query:

SELECT NEW com.java2s.common.EmployeeDetails(e.name, e.salary, e.department.name) FROM Employee e

how can I pass null to constructor (as 3rd argument) if e.department is null?

I guess e.department.name will result in an exception if e.department is null?


Solution

  • I guess e.department.name will result in an exception if e.department is null?

    No. e.department.name does an implicit inner join between the Employee and the Departement tables. So if an employee doesn't have any department, then the employee won't even be returned by the query.

    If you want employees without a department to be selected, you need a left join:

    select new com.java2s.common.EmployeeDetails(e.name, e.salary, d.name)  
    from Employee e
    left join e.department d
    

    The above query would return the name and the salary of the employee, and null as the name of the department if the employee doesn't have a department.

    Note: experimenting is a really good way of transforming guesses into facts. Why don't you try that query instead of guessing what it will do?