JPA Query with wildcards

Here is a short tip on using LIKE expression with JPA .

What we are trying to do is get all the items that matches a pattern anywhere in their name.

In simple SQL, what I want to do is:

SELECT userName FROM Profile p WHERE p.userName LIKE %pattern%;

I'm using annotations to create a named query.

@NamedQuery(name="Profile.getUsernameWithPattern", 
query="SELECT p FROM Profile p WHERE p.userName LIKE ?1 ORDER BY p.userName ASC")

(This will even sort the result!!)

Here's the code that demonstrates using this query:

 Query query = strategy.getNamedQuery("Profile.getUsernameWithPattern");
 query.setParameter(1, "%" + pattern + "%");        
 query.getResultList();

Hope you found this tip helpful!

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

manveen

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today