Spring data @Query:如果给定了可选的布尔参数,则检查 where 子句中其他字符串列的大小
Spring data @Query: If optional Boolean param is given check size of other String column in where clause
我试图在我的一个存储库中构建一个@Query,它在我的示例中获得了一个名为 "hasComment" 的可选布尔参数。如果布尔值是 given/exists,我想对 where 子句中的另一个字符变化列 ("comment") 进行长度检查。
我目前有以下代码,我不希望它工作(当然不是)但它应该显示我想象它如何工作的方式。
@Query("SELECT t "
+ "FROM Test t "
+ "WHERE "
+ "(:from IS NULL OR t.startTs >= :from) "
+ "AND (:to IS NULL OR t.endTs <= :to) "
+ "AND ((:hasComment) IS NULL OR ("
+ "(CASE WHEN :hasComment = true THEN length(t.comment) > 0)"
+ "OR (CASE WHEN :hasComment = false THEN length(t.comment) = 0 OR t.comment IS NULL)"
+ ")"
Page<Test> find(@Param("from") Instant from, @Param("to") Instant to,
@Param("hasComment") Boolean hasComment, Pageable pageable);
有人能帮帮我吗?我只是无法真正找到有关如何构建此查询的信息,即使这完全可以使用 @Query...
我认为不可能在 WHERE 条件中使用 CASE。
关于您的查询,有一个解决方法
"AND (:to IS NULL OR t.endTs <= :to) "
+ "AND ((:hasCategory) IS NULL OR ("
+ "(CASE WHEN :hasCategory = true THEN length(t.comment) > 0)"
+ "OR (CASE WHEN :hasCategory = false THEN length(t.comment) = 0 OR t.comment IS NULL)"
+ ")"
至
AND ((:hasCategory) IS NULL OR (
(:hasCategory=true AND length(t.comment)>0) OR
(:hasCategory = false AND length(t.comment) = 0) OR
(:hasCategory = false AND t.comment IS NULL))
)
我试图在我的一个存储库中构建一个@Query,它在我的示例中获得了一个名为 "hasComment" 的可选布尔参数。如果布尔值是 given/exists,我想对 where 子句中的另一个字符变化列 ("comment") 进行长度检查。
我目前有以下代码,我不希望它工作(当然不是)但它应该显示我想象它如何工作的方式。
@Query("SELECT t "
+ "FROM Test t "
+ "WHERE "
+ "(:from IS NULL OR t.startTs >= :from) "
+ "AND (:to IS NULL OR t.endTs <= :to) "
+ "AND ((:hasComment) IS NULL OR ("
+ "(CASE WHEN :hasComment = true THEN length(t.comment) > 0)"
+ "OR (CASE WHEN :hasComment = false THEN length(t.comment) = 0 OR t.comment IS NULL)"
+ ")"
Page<Test> find(@Param("from") Instant from, @Param("to") Instant to,
@Param("hasComment") Boolean hasComment, Pageable pageable);
有人能帮帮我吗?我只是无法真正找到有关如何构建此查询的信息,即使这完全可以使用 @Query...
我认为不可能在 WHERE 条件中使用 CASE。 关于您的查询,有一个解决方法
"AND (:to IS NULL OR t.endTs <= :to) "
+ "AND ((:hasCategory) IS NULL OR ("
+ "(CASE WHEN :hasCategory = true THEN length(t.comment) > 0)"
+ "OR (CASE WHEN :hasCategory = false THEN length(t.comment) = 0 OR t.comment IS NULL)"
+ ")"
至
AND ((:hasCategory) IS NULL OR (
(:hasCategory=true AND length(t.comment)>0) OR
(:hasCategory = false AND length(t.comment) = 0) OR
(:hasCategory = false AND t.comment IS NULL))
)