SQL 'LIKE' operator in Hibernate Criteria API

后端 未结 5 1467
萌比男神i
萌比男神i 2020-12-16 14:55

I want to implement some universal filter with Hibernate Criteria. It should work like LIKE operator from SQL:



        
相关标签:
5条回答
  • 2020-12-16 15:21

    when field type is not String, it couse java.lang.ClassCastException

    thats because it only works with string/varchar fields/columns.

    0 讨论(0)
  • 2020-12-16 15:23

    Use the enum MatchMode to help you with it:

    Criterion c1 = Restrictions.like("AttributeName", "AttributeValue", MatchMode.END);
    

    Don't use any special character, like * Referencce Read This Like

    0 讨论(0)
  • 2020-12-16 15:35

    I recommend using a Query object instead of the Criteria object, in this case.

    I can't remember if Criteria passes things it doesn't understand straight through to the database like a Query object will do. Basically what this would mean is that if you used a function that was database specific that the Hibernate parser didn't understand, it would pass it "as is" to the database.

    Example:

    Query queryObject = session.createQuery("from ClassName where VARIABLENAME like '%'||anyvaluehere||'%' order by VARIABLENAME");
    List<YourClass> resultList= queryObject.list();
    

    For more see here

    0 讨论(0)
  • 2020-12-16 15:39

    You can use DetachedCriteria also when the hibernate session is not present.

    DetachedCriteria criteria = DetachedCriteria.forClass(Pojo.class);
    criteria.add(Restrictions.like("column", value, MatchMode.ANYWHERE));
    

    It will match the value anywhere in the column string. You can use different types of modes.

    Reference page: https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/criterion/MatchMode.html

    DetachedCriteria:

    - Detached criteria is very good alternate when the hibernate session is not present.

    Using a DetachedCriteria is exactly the same as a Criteria except you can do the initial creation and setup of your query without having access to the session. When it comes time to run your query, you must convert it to an executable query with getExecutableCriteria(session).

    This is useful if you are building complicated queries, possibly through a multi-step process, because you don't need access to the Session everywhere. You only need the Session at the final step when you run the query.

    Under the hood, DetachedCriteria uses a CriteriaImpl which is the same class you get if you call session.createCriteria().

    0 讨论(0)
  • 2020-12-16 15:41

    You can use like() restriction criteria like this:

    session = sessionFactory.openSession();
    Criteria query = session.createCriteria(Pojo.class);
    query.add(Restrictions.like("anycolumn", "anyvalue", MatchMode.START));
    

    It will give you a list of strings that start with "anyvalue".

    0 讨论(0)
提交回复
热议问题