Search code examples
javahibernatehql

Do I have to defensively protect nulls in my hql query?


Say I have an company with a phone number. I might have a lead record and I want to get leads for a phone number. Do I have to ensure my company is not null first?

Option 1

FROM Lead l WHERE l.company IS NOT NULL AND l.company.phone = :phone

Option 2

FROM Lead l WHERE l.company.phone = :phone

In option 1 I'm making sure company is not null before I check for phone. In option 2 I assume hibernate has a way to short circuit that.

I've tried looking but can't find documentation on this fact. I'm also on mobile atm so that is hampering my search (and my posting this!)


Solution

  • No, you don't. where l.company.phone = :phone is equivalent to inner join l.company c where c.phone = :phone, and an inner join will simply filter out the entities which have a null company.

    Those queries are ultimately transformed to SQL and executed by the database. They don't use your Java entities. The corresponding SQL query would look like

    from lead l, company c where l.company_id = c.id and c.phone = :phone
    

    A simple test would have allowed you to find out by yourself, BTW.