开发者

MySQL condition in where-clause of a JPA named query with nullable attribute as parameter

开发者 https://www.devze.com 2023-03-13 17:11 出处:网络
How can a condition be specified in a where-clause of a JPA named query for a MySQL 5.1 database, in case some of the attributes which are passed as parameter are nullable?

How can a condition be specified in a where-clause of a JPA named query for a MySQL 5.1 database, in case some of the attributes which are passed as parameter are nullable?

Example: The table contains attribute_1 which is nullable and attribute_2 which is not nullable. The contents are:

    id    attribute_1    attribute_2
    --    -----------    -----------
    1     {null}          123
    2     X               456

The query result should be re开发者_Python百科cord 1 if :param_1 = null AND :param_2 = "123"

The query result should be record 2 if :param_1 = "X" AND :param_2 = "456"

The query should have no result if for example :param_1 = "X" AND :param_2 = "123"

Thanks!


I solved the problem by using a native query. I cannot get it work with a JP-QL query. I used the condition

AND IF(?1 IS NULL, b.attribute_1 IS NULL, b.attribute_1 = ?1)

in the where clause (?1 is the placeholder for the parameter).


For your first row, you need to change the where clause in your query:

where attribute_1 is null

Using = instead would yield no rows, since a = null is always null.

0

精彩评论

暂无评论...
验证码 换一张
取 消