Im facing simple problem with searching entities by some (sub)string, which they might contain.
E.g. I have users user1, usr2, useeeer3, user4 and I will enter to search window "use" and I expect to return user1, useeer3, user4.
Im sure you know what I mean now. Is there any construction in JPA (JQPL)? It would be nice to search using WHERE somehow in named queries. Something like "SELECT u FROM User u WHERE u.nickname contains :substring"
Use a LIKE
expression. Here is a quote from the section 4.6.9 Like Expression of the JPA 1.0 spec (JSR 220):
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 inpattern_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
orpattern_value
isNULL
or unknown, the value of the LIKE expression is unknown. If theescape_character
is specified and isNULL
, the value of the LIKE expression is unknown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With