user1727939
user1727939

Reputation:

JPA: How to check NULL query-parameter value with HQL?

Query query =  em.createQuery(
        "select count(u) from User u where (u.id=:a) and (u.photo=:b)")
        .setParameter("a",userId).setParameter("b",null);

In my case, I want check whether user photo uploaded or not (photo value is null or not). I tried above query.

Upvotes: 7

Views: 21169

Answers (2)

zakmck
zakmck

Reputation: 3004

If you're aiming at generalising "b", so that a method can receive either a given search value, or a null, this usually works:

Query q = em.createQuery (
  "SELECT ... WHERE ... ( :b IS NULL AND u.photo IS NULL OR u.photo = :b )" 
);
q.setParameter ( "b", searchValue ); // can be null
...

There is an helper to use this approach here (see parameterizedWithNullHql()).

Upvotes: 7

Taky
Taky

Reputation: 5344

See example in Hibernate documentation.

You should check is parameter is null:

Query query =  em.createQuery(
        "select count(u) from User u where (u.id=:userId) and (u.photo is null)")
        .setParameter("userId",userId);

Upvotes: 11

Related Questions