和SQL查询一样,Hibernate,HQL使用like关键字进行模糊查询。模糊查询能够比较字符串是否与指定的字符串模式匹配。其中使用通配符表示:如下

%(百分号):匹配任意类型、任意长度的字符串,中文则需要两个百分号"%%"

_(下划线):匹配单个任意字符,一般用来限制字符串表达式的长度。

下面举例说明:

1.检索姓名以"M"开头的同学:

 

 
  
  1. String queryString="from studentInfo s where s.sname like 'S%'"

2.检索姓名中包含字符串"abc"的学生对象:

 
  
  1. String queryString="from studentInfo s where s.sname like '%abc%'"


3.检索以S开头,并且字符串长度为5的学生对象:
 

 
  
  1. String queryString="from studentInfo s where s.sname like 'S____'"; 四个下划线"_" 


4.实例:检索学生姓名中含有"王"的所有学生:
 

 

 
  
  1. String queryString = "from StudentInfo s where s.sname like'%"+sname+"%'";  注意这个HQL语句的拼接部分,不能写错! 


DAO如下:
 

 
  
  1. public List findBySname(Object sname) {  
  2.         log.debug("finding all StudentInfo instances");  
  3.         try {  
  4.             //String queryString = "from StudentInfo s where s.name like '%"+sname+"%'";  
  5.             String queryString = "from StudentInfo s where s.sname like'%"+sname+"%'";  
  6.             Query queryObject = getSession().createQuery(queryString);  
  7.             return queryObject.list();  
  8.               
  9.         } catch (RuntimeException re) {  
  10.             log.error("find all failed", re);  
  11.             throw re;  
  12.         }  
  13.     } 

页面即可输出这个List集合了。