Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIKE restriction from the Hibernate Criteria API

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

}
like image 971
Biggy_java2 Avatar asked Jan 10 '13 18:01

Biggy_java2


People also ask

What is restriction in Hibernate criteria?

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.

How do you put restrictions in criteria query?

Restrictions with CriteriaCriteria cr = session. createCriteria(Employee. class); Criterion salary = Restrictions.gt("salary", 2000); Criterion name = Restrictions.

Where you will use criteria API of Hibernate?

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.


1 Answers

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.

like image 166
Juliano Alves Avatar answered Sep 22 '22 15:09

Juliano Alves