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!
Posted at 11:01AM Feb 26, 2008 by Manveen Kaur in General | Comments[0]