7
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.

2 Answers 2

11

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);
Sign up to request clarification or add additional context in comments.

Comments

7

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()).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.