I am trying to query PostgreSQL database using Hibernate's restriction criterion like()
with a partial keyword:
Criterion c1 = Restrictions.like("stateName", "Virg*");
cri.add(c1);
return cri.list();
It doesn't return anything but Restrictions.like("stateName", "Virginia");
returns the correct record. How do I use partial like restrictions in Hibernate?
EDIT:
Got it working by doing something like this:
public static List<Object> createQueryStringByRegex(Criteria cri, Parameters p) {
String value = (String) p.value;
if (value.contains("*")) {
value = value.replace("*", "%");
} else {
value += "%";
}
// System.out.println("Value: "+value);
Criterion c1 = Restrictions.ilike(p.property, value);
cri.add(c1);
return cri.list();
}
The Criteria interface makes it easy to selectively fetch the data on the basis of conditions in the select query. The Restriction class in hibernate provide several methods that can be used as conditions (also known as Criterion). These conditions are added to a criteria object with the add() method.
Restrictions with CriteriaCriteria cr = session. createCriteria(Employee. class); Criterion salary = Restrictions.gt("salary", 2000); Criterion name = Restrictions.
Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
Use the enum MatchMode to help you with it:
Criterion c1 = Restrictions.like("stateName", "Virg", MatchMode.START);
Don't use any special character, like *. And if you want a case-insensitive like, use ilike.
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