Hibernate模糊查询
和SQL查詢一樣,Hibernate,HQL使用like關(guān)鍵字進(jìn)行模糊查詢。模糊查詢能夠比較字符串是否與指定的字符串模式匹配。其中使用通配符表示:如下
%(百分號(hào)):匹配任意類型、任意長度的字符串,中文則需要兩個(gè)百分號(hào)"%%"
_(下劃線):匹配單個(gè)任意字符,一般用來限制字符串表達(dá)式的長度。
下面舉例說明:
1.檢索姓名以"M"開頭的同學(xué):
?
String queryString="from studentInfo s where s.sname like 'S%'";
2.檢索姓名中包含字符串"abc"的學(xué)生對(duì)象:
String queryString="from studentInfo s where s.sname like '%abc%'";
?
3.檢索以S開頭,并且字符串長度為5的學(xué)生對(duì)象:
?
String queryString="from studentInfo s where s.sname like 'S____'"; 四個(gè)下劃線"_"
?
4.實(shí)例:檢索學(xué)生姓名中含有"王"的所有學(xué)生:
?
?
String queryString = "from StudentInfo s where s.sname like'%"+sname+"%'";? 注意這個(gè)HQL語句的拼接部分,不能寫錯(cuò)!
?
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;?
??????? }?
??? }
頁面即可輸出這個(gè)List集合了。
總結(jié)
以上是生活随笔為你收集整理的Hibernate模糊查询的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript操作select标签
- 下一篇: 拦截器Intercepter和过滤器Fi