如何在Spring Data JPQL LIKE查询中转义'_'和'%'通配符?



我在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>

当标题包含_或%chars时,Spring数据将它们作为通配符传递,而不是作为文字传递。示例:我在数据库中有一个标题为"bug_with_underscore"的音调。web UI上的用户通过">"查找标题中文字为">"的音调,但实际结果包括所有音调。

如何在LIKE查询中设置自动字符转义?

春季数据JPA:2.3.5 版本

我找到了几种可能的解决方案:

  1. 使用concat并替换SQL函数:https://stackoverflow.com/questions/30740432/escaping-values-in-spring-data-repository
  2. 在将通配符传递给查询之前屏蔽通配符:https://stackoverflow.com/questions/53558667/java-jpa-sql-accept-wrong-with-like

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-有序参数

最新更新