Hibernate QBC中like查询和MatchMode的四种模式

时间:2020-12-25 16:41:16
MatchMode.START:字符串前面位置.相于"like 'key%'"
MatchMode.END:字符串面位置.相于"like '%key'"
MatchMode.ANYWHERE:字符串间匹配.相于"like '%key%'"

MatchMode.EXACT:字符串精确匹配.相于"like 'key'"


例子1:
Restrictions.or(Restrictions.like(),Restrictions.or(Restrictions.like,........))

Session session = getHibernateTemplate().getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Film.class);
List<Film> list = criteria.add(
Restrictions.or(Restrictions.like("description", key,MatchMode.ANYWHERE),
Restrictions.or(Restrictions.like("name", key,MatchMode.ANYWHERE),
Restrictions.or(Restrictions.like("direct", key,MatchMode.ANYWHERE),
Restrictions.or(Restrictions.like("mainplay",key,MatchMode.ANYWHERE),
Restrictions.like("filearea", key,MatchMode.ANYWHERE)))))).list();
session.close();
return list;


例子2:
User表数据如下
ID address
1  a,b
2  aaa,bbb,ccc
3  a,aaa
4  b
如果用户要查询address包含a或者b(完全匹配)的结果集,那么结果ID=1、3、4。

String[] pageAddress = {"a", "b"};
Session session = getHibernateTemplate().getSessionFactory().openSession();
Criteria criteria = session.createCriteria(User.class);
if(pageAddress != null && pageAddress.length>0 && !"".equals(pageAddress[0])) {
for (int i = 0; i < pageAddress.length; i++) {
criteria.add(
Restrictions.or(Restrictions.like("address", pageAddress[i]+",", MatchMode.START),
Restrictions.or(Restrictions.like("address", ","+pageAddress[i], MatchMode.END),
Restrictions.or(Restrictions.like("address", pageAddress[i], MatchMode.EXACT),
Restrictions.like("address", ","+pageAddress[i]+",", MatchMode.ANYWHERE))))));
}
}