Search code examples
javaspringvalidationspring-dataspring-data-jpa

Validate collection is not empty in Spring Data query parameter


Let's say I have a Spring Data repository with query method

public interface SomeRepository extends JpaRepository<Something, Long> {

    @Query("select s from Something s where s.val in :values")
    List<Something> findSomethingsByValIn(@Param("values") Collection<Long> values);
}

When passed Collection of values is empty, I've got

SQL Error: 1064, SQL State: 42000
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '))' at line 1

because of something like

Hibernate: select something0_ as col_0_0_ from Something something0_ where something0_.val in ())

Of course, I could easily check passed parameter before method calling. And I even could describe it in javadoc. But is it possible to validate argument inside query method?


Solution

  • I'd argue checking the collection for emptiness beforehand is the way to go here because in that particular case there's no need to even execute the database query.

    I guess one could argue that MariaDB could be less picky about the empty collection being passed to the query but I guess they consider it an application level error. You can find arguments for both sides of the story here.

    That said, if you want to check the parameter inside the method, you'll have to resort to a custom implementation method as described in the reference documentation.