JPQL 可以对枚举执行 LIKE 表达式吗?
如果我有一个带有枚举字段 bar 的实体 Foo,我可以在 MySQL 中执行以下操作(bar 存储为 MySQL 枚举)...
SELECT * FROM Foo WHERE `bar` LIKE '%SUFFIX'
但是,JPQL中对应的查询...
SELECT f FROM Foo f WHERE f.bar LIKE '%SUFFIX'
...提示...
Parameter value [%SUFFIX] was not matching type [com.example.Foo$EnumType]
最佳答案
我认为这是不可能的,LIKE
的左侧部分应该是一个string_expression(在标准 JPA 中)。来自规范:
4.6.9 Like Expressions
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
orCharacter
) and is used to escape the special meaning of the underscore and percent characters in pattern_value.
enum_expression 不是string_expression。
下面的方法可以工作(使用enum literals):
SELECT f
FROM Foo f
WHERE f.bar = com.acme.Bar.SOME_CONSTANT
OR f.bar = com.acme.Bar.SOME_OTHER_CONSTANT
另一种选择是将 bar
字段实际存储为 String
(并在 getter/setter 中对枚举进行一些转换)。
引用
- JPA 1.0 规范
- 第 4.6.9 节“喜欢的表达方式”
- 第 4.14 节“BNF”
关于java - 枚举上的 JPQL LIKE 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3668402/