验证 Spring 数据查询参数中的集合不为空
Validate collection is not empty in Spring Data query parameter
假设我有一个 Spring 带有查询方法的数据存储库
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);
}
当传递的值集合为空时,我得到了
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
因为类似
Hibernate: select something0_ as col_0_0_ from Something something0_ where something0_.val in ())
当然,我可以在方法调用之前轻松检查传递的参数。我什至可以用 javadoc 来描述它。但是是否可以在查询方法中验证参数?
我认为事先检查集合是否为空是正确的方法,因为在那种特殊情况下甚至不需要执行数据库查询。
我猜有人可能会争辩说 MariaDB 对传递给查询的空集合可能不那么挑剔,但我猜他们认为这是一个应用程序级错误。你可以在这里找到故事双方的论据。
也就是说,如果您想检查方法内部的参数,您将不得不求助于 reference documentation 中描述的自定义实现方法。
假设我有一个 Spring 带有查询方法的数据存储库
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);
}
当传递的值集合为空时,我得到了
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
因为类似
Hibernate: select something0_ as col_0_0_ from Something something0_ where something0_.val in ())
当然,我可以在方法调用之前轻松检查传递的参数。我什至可以用 javadoc 来描述它。但是是否可以在查询方法中验证参数?
我认为事先检查集合是否为空是正确的方法,因为在那种特殊情况下甚至不需要执行数据库查询。
我猜有人可能会争辩说 MariaDB 对传递给查询的空集合可能不那么挑剔,但我猜他们认为这是一个应用程序级错误。你可以在这里找到故事双方的论据。
也就是说,如果您想检查方法内部的参数,您将不得不求助于 reference documentation 中描述的自定义实现方法。