Manuel M
Manuel M

Reputation: 859

Hibernate WHERE does not work for @Embedded with null member

I have a class Posting with an @Embedded:

public class Posting {
  @Embedded
  private BankDetails bankDetails;      
}

public class BankDetails {
    private String bankCode;
    private String bankName;
}

Now I want to list all Postings with a bankCode of 123 and a bankName of null.

Query q = entityManager.createQuery("SELECT o from Posting o WHERE bankDetails=?");
q.setParameter(1, new BankDetails("123", null));

However I don't get any results.

Why?

Here's the sql query Hibernate executes:

select posting0_.bank_code as bank_cod6_42_, posting0_.bank_name as bank_nam7_42_
from posting posting0_ 
where (posting0_.bank_code, posting0_.bank_name)=('123', null)

(Btw, this parentheses syntax is called Row Value Constructors.)

That obviously does not work because is compares null with =.

  1. Is this a bug? If yes, which component generates the SQL statement? (Hibernate? the mysql-connector?)
  2. Any ideas for a workaround?

Environment: MySQL Server 5.7 on Win10, Spring 4.0.3, Hibernate 4.3.11, mysql-connector 5.1.30

Upvotes: 1

Views: 246

Answers (2)

Manuel M
Manuel M

Reputation: 859

This is a bug in Hibernate 4 and 5.

It should be fixed in Hibernate 6: https://hibernate.atlassian.net/browse/HHH-8172

See @Naros answer for a workaround.

Upvotes: 0

Naros
Naros

Reputation: 21113

Yes there is a workaround, but it requires you to be a bit more verbose with the query.

entityManager.createQuery( "SELECT o FROM Posting o WHERE " +
    " o.bankDetails.bankCode = ? " +
    " AND o.bankDetails.bankName IS NULL" );
entityManager.setParameter( 1, "123" );

I honestly haven't seen a query generated with a tuple value like that, but most of my past experience has been with SQL Server that does not support such a syntax. If you believe it's a bug, please feel free to open a JIRA issue.

Upvotes: 1

Related Questions