和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集合瞭。
本文出自 “幽靈柯南的技術blog” 博客