3

I have a N-N Product-Category model, and I've made a Spring Data JPA @Query to retrieve products of a given category (or all products if category is null):

@Query("SELECT DISTINCT obj FROM Product obj INNER JOIN obj.categories cats WHERE "
    + "(:category IS NULL OR :category IN cats)")
Page<Product> find(Category category, Pageable pageable);

It works perfectly in H2 database. However, when testing in Postgres 12, if a null category is given, I get the following error:

org.postgresql.util.PSQLException: ERROR: operator does not exist: bytea = bigint
  Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

Coalesce saved me once in the past for similar issue with a parameter of type Instant, but this time it did NOT solve the problem for an entity parameter:

    + "(COALESCE(:category, NULL) IS NULL OR :category IN cats)")

Just in case, I've tested only for NULL and it doesn't throw any errors for both null and not null categories:

    + "(:category IS NULL")

I've also tested only the IN clause, and got the same "operator does not exist" error when a null category is given:

    + "(:category IN cats)")

Tests have shown that, apparently, the :category IS NULL condition before OR operator is not preventing the :category IN cats of being evaluated. How can I solve this problem?

1
  • 1
    Hey Nelio, did you find any solution for that? I'm facing the same problem Commented May 12, 2021 at 21:46

1 Answer 1

2

After facing the same problem as you and tried several different solutions I found one that works fine with postgreSQL.

Instead passing the list as null you can pass the list as a emptyList()

So I add a Ternary at my code to validate if the parameter is null if so I pass a Collections.emptyList();

Hope this help you too :)

Sign up to request clarification or add additional context in comments.

1 Comment

You're a life savior!! Simple and ellegant. Thanks man

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.