SQL 'LIKE' operator in Hibernate Criteria API

放肆的年华 提交于 2019-11-29 03:41:39

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

MayurB

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".

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

Shaam

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

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

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

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