Hibernate模糊查询

来源:互联网 发布:上海网络推广哪家好 编辑:程序博客网 时间:2024/05/18 02:57

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

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

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

下面举例说明:

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

 

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

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

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

 

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

 

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

 

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

 

 

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

 

DAO如下:

 

public List findBySname(Object sname) { 

        log.debug("finding all StudentInfo instances"); 

        try { 

            //String queryString = "from StudentInfo s where s.name like '%"+sname+"%'"; 

            String queryString = "from StudentInfo s where s.sname like'%"+sname+"%'"; 

            Query queryObject = getSession().createQuery(queryString); 

            return queryObject.list(); 

             

        } catch (RuntimeException re) { 

            log.error("find all failed", re); 

            throw re; 

        } 

    }

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

原创粉丝点击