LIKE restriction from the Hibernate Criteria API

◇◆丶佛笑我妖孽 提交于 2019-12-05 13:08:14

问题


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

}

回答1:


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.




回答2:


The restriction should use the percent symbol.

Criterion c1 = Restrictions.like("stateName", "Virg%");



回答3:


##Use MatchMode.ANYWHERE##
DetachedCriteria crit = DetachedCriteria.forClass(MyClass.class);
 crit.add(Restrictions.like("prop1", "matchValue", MatchMode.ANYWHERE));
 return getHibernateTemplate().findByCriteria(crit);


来源:https://stackoverflow.com/questions/14264513/like-restriction-from-the-hibernate-criteria-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!