Hibernate模糊查询

 Hibernate模糊查询
2011-07-31 12:24:32

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://enetq.blog.51cto.com/479739/627847

和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. } catch (RuntimeException re) {
  9. log.error("find all failed", re);
  10. throw re;
  11. }
  12. }

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

本文出自 “幽灵柯南的技术blog” 博客,请务必保留此出处http://enetq.blog.51cto.com/479739/627847

posted @ 2013-04-23 09:09  眉间尺之魂  阅读(1149)  评论(0编辑  收藏  举报