简体   繁体   English

在 JPA 中使用正则表达式搜索

[英]search using regex in JPA

I am trying to do a simple search function by multiple words, like this in SQL query我正在尝试通过多个单词进行简单的搜索 function,例如 SQL 查询

SELECT * FROM faqs WHERE title REGEXP 'préférée|Changer|endommagé' or question REGEXP 'préférée|Changer|endommagé'

but when I tried to implement this in @Query in my JpaRepository like this但是当我试图在我的 JpaRepository 中的@Query中实现这个时

@Query(value = "SELECT f FROM Faq f WHERE f.title REGEXP :term" )
Page<Faq> searchByRegExp(@Param("term") String term,Pageable pageable);

But it seems that REGEXP isnt supported because of this error:但由于此错误,似乎不支持REGEXP

<expression>, <operator>, GROUP, HAVING or ORDER expected, got 'REGEXP'

Note: I tried adding nativeQuery = true - same issue:注意:我尝试添加nativeQuery = true - 同样的问题:

@Query(value = "SELECT * FROM faqs WHERE title REGEXP :term ", nativeQuery = true)
    Page<Faq> searchByRegExp(@Param("term") String term,Pageable pageable);

Unfortunately jpql does not support regular expressions.不幸的是 jpql 不支持正则表达式。 You would have to use like and write all the possibilities.您将不得不使用like并编写所有可能性。 But in your case you can simply use in :但在您的情况下,您可以简单地使用in

@Query(value = "SELECT f FROM Faq f WHERE f.title in (:terms)" )
Page<Faq> searchByRegExp(@Param("terms") List<String> terms, Pageable pageable);

And as the first parameter pass the possibilities: List.of("préférée", "Changer", "endommagé") .并且作为第一个参数传递的可能性: List.of("préférée", "Changer", "endommagé") For more complex regular expressions this list would grow considerably, but in this case only 3 values are possible.对于更复杂的正则表达式,这个列表会大大增加,但在这种情况下,只有 3 个值是可能的。

The other way is using nativeQuery and sql:另一种方法是使用nativeQuery和 sql:

@Query(value = "SELECT f.* FROM faqs f WHERE (f.title REGEXP :term)", nativeQuery = true)
Page<Faq> searchByRegExp(@Param("term") String term,Pageable pageable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM