LIKE restriction from the Hibernate Criteria API

Biggy_java2 picture Biggy_java2 · Jan 10, 2013 · Viewed 51.7k times · Source

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();

}

Answer

Juliano Alves picture Juliano Alves · Jan 10, 2013

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.