我在Spring数据存储库中有以下方法:
@Query("""
select t from ToneEntity t
where (:title is null or (t.title like %:title%))
and (:albumId is null or (t.album.id = :albumId))
and (:artistId is null or (t.artist.id = :artistId))
and (:creatorId is null or (t.creator.id = :creatorId))
""")
fun findFilteredTones(
@Param("title") title: String?,
@Param("albumId") albumId: Long?,
@Param("artistId") artistId: Long?,
@Param("creatorId") creatorId: Long?,
pageable: Pageable
): List<ToneEntity>
当标题包含 _ 或 % 字符时,Spring 数据将它们作为通配符传递,而不是作为文字传递。 示例:我在数据库中有一个标题为“bug_with_underscore”的音调。 Web UI 上的用户通过“”来查找标题中带有“”文字的音调,但实际结果包括所有音调。
如何在 LIKE 查询中设置自动字符转义?
Spring Data JPA 版本:2.3.5
我找到了几种可能的解决方案:
2022年还有更好的解决方案吗?到目前为止,我还没有找到比使用方面手动转义通配符更好的方法。因为这个问题在我们的项目中经常出现
这可能对您有帮助,但不幸的是它对我没有帮助,因为这种语法在 Spring Boot 3 中不再有效。我确实在 Spring Boot 2 中尝试过它并且它有效。它是用 Java 编写的,但查询部分应该没有任何不同。
@Query("SELECT m FROM Movie m WHERE m.director LIKE %?#{escape([0])} escape ?#{escapeCharacter()}")
List<Movie> searchByDirectorEndsWith(String director);
来源:https://www.baeldung.com/spring-jpa-like-queries#2-ordered-parameters
我遇到了同样的问题,我使用 EscapeCharacter 通过包装像
这样的值来解决它searchKey = EscapeCharacter.DEFAULT.escape(searchKey)