java - JPQL (JPA) 搜索子字符串

标签 java orm jpa jpql

我面临着一个简单的问题,即通过实体可能包含的某些(子)字符串搜索实体。

例如我有用户 user1、usr2、useeeer3、user4,我将进入搜索窗口“use”,我希望返回 user1、useeer3、user4。

我相信你现在明白我的意思了。 JPA(JQPL)中有构造吗?在命名查询中以某种方式使用 WHERE 进行搜索会很好。类似于“SELECT u FROM User u WHERE u.nickname contains :substring”

最佳答案

使用 LIKE 表达式。以下是 JPA 1.0 规范 (JSR 220) 的 4.6.9 Like Expression 部分的引述:

The syntax for the use of the comparison operator [NOT] LIKE in a conditional expression is as follows:

string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]

The string_expression must have a string value. The pattern_value is a string literal or a string-valued input parameter in which an underscore (_) stands for any single character, a percent (%) character stands for any sequence of characters (including the empty sequence), and all other characters stand for themselves. The optional escape_character is a single-character string literal or a character-valued input parameter (i.e., char or Character) and is used to escape the special meaning of the underscore and percent characters in pattern_value.

Examples are:

  • address.phone LIKE ‘12%3’ is true for ‘123’ ‘12993’ and false for ‘1234’
  • asentence.word LIKE ‘l_se’ is true for ‘lose’ and false for ‘loose’
  • aword.underscored LIKE ‘\_%’ ESCAPE ‘\’ is true for ‘_foo’ and false for ‘bar’
  • address.phone NOT LIKE ‘12%3’ is false for ‘123’ and ‘12993’ and true for ‘1234’

If the value of the string_expression or pattern_value is NULL or unknown, the value of the LIKE expression is unknown. If the escape_character is specified and is NULL, the value of the LIKE expression is unknown.

关于java - JPQL (JPA) 搜索子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747887/

相关文章:

java - HIbernate 加载子类和类

java - 组织.hibernate.QueryException : could not resolve property

java - 错误 java.lang.InstantiationException

java - 使用 WebSphere Message Broker (WMB) 将 CSV 文件转换为 Java 对象

java - subscribeOn 新线程有时不返回

android - GreenDao 多对多关系

java - org.hibernate.PropertyAccessException : Could not set field value [STRING] value by reflection for String

java - 在 Java 中转换字节后正值如何变为负值?

java - 如何编写 @QueryResult 类以正确捕获密码结果。 (未经反复试验)

java - 使用 "in"过滤器的子查询删除