方法sql |
說明session |
Restrictions.eqless |
=spa |
Restrictions.allEqhibernate |
利用Map來進行多個等於的限制對象 |
Restrictions.gt排序 |
>ip |
Restrictions.geci |
>=字符串 |
Restrictions.lt |
< |
Restrictions.le |
<= |
Restrictions.between |
BETWEEN |
Restrictions.like |
LIKE |
Restrictions.in |
in |
Restrictions.and |
and |
Restrictions.or |
or |
Restrictions.sqlRestriction |
用SQL限定查詢 |
Restrictions.eq --> equal,等於.
Restrictions.allEq --> 參數爲Map對象,使用key/value進行多個等於的比對,至關於多個Restrictions.eq的效果
Restrictions.gt --> great-than > 大於
Restrictions.ge --> great-equal >= 大於等於
Restrictions.lt --> less-than, < 小於
Restrictions.le --> less-equal <= 小於等於
Restrictions.between --> 對應SQL的between子句
Restrictions.like --> 對應SQL的LIKE子句
Restrictions.in --> 對應SQL的in子句
Restrictions.and --> and 關係
Restrictions.or --> or 關係
Restrictions.isNull --> 判斷屬性是否爲空,爲空則返回true
Restrictions.isNotNull --> 與isNull相反
Restrictions.sqlRestriction --> SQL限定的查詢
Order.asc --> 根據傳入的字段進行升序排序
Order.desc --> 根據傳入的字段進行降序排序
MatchMode.EXACT --> 字符串精確匹配.至關於"like 'value'"
MatchMode.ANYWHERE --> 字符串在中間匹配.至關於"like '%value%'"
MatchMode.START --> 字符串在最前面的位置.至關於"like 'value%'"
MatchMode.END --> 字符串在最後面的位置.至關於"like '%value'"
例子
查詢年齡在20-30歲之間的全部學生對象
List list = session.createCriteria(Student.class)
.add(Restrictions.between("age",new Integer(20),new Integer(30)).list();
查詢學生姓名在AAA,BBB,CCC之間的學生對象
String[] names = {"AAA","BBB","CCC"};
List list = session.createCriteria(Student.class)
.add(Restrictions.in("name",names)).list();
查詢年齡爲空的學生對象
List list = session.createCriteria(Student.class)
.add(Restrictions.isNull("age")).list();
查詢年齡等於20或者年齡爲空的學生對象
List list = session.createCriteria(Student.class)
.add(Restrictions.or(Restrictions.eq("age",new Integer(20)),
Restrictions.isNull("age")).list();
--------------------------------------------------------------------
使用QBC實現動態查詢
public List findStudents(String name,int age){
Criteria criteria = session.createCriteria(Student.class);
if(name != null){
criteria.add(Restrictions.liek("name",name,MatchMode.ANYWHERE));
}
if(age != 0){
criteria.add(Restrictions.eq("age",new Integer(age)));
}
criteria.addOrder(Order.asc("name"));
return criteria.list();
}
-----------------------------------------------------------------------------------
寫hibernate高級查詢時用了Restrictions(固然Expression也是能夠的)這個類.感受不錯.下面的代碼其實核心就是一句Restrictions.or(Restrictions.like(),Restrictions.or(Restrictions.like,........))裏面的or能夠無限加的.仍是比較好用Session session = getHibernateTemplate().getSessionFactory() .openSession(); Criteria criteria = session.createCriteria(Film.class); List<Film> list = criteria.add( Restrictions.or(Restrictions.like("description", key,MatchMode.ANYWHERE), Restrictions.or(Restrictions.like("name", key,MatchMode.ANYWHERE), Restrictions.or( Restrictions.like("direct", key,MatchMode.ANYWHERE), Restrictions.or(Restrictions.like("mainplay",key,MatchMode.ANYWHERE), Restrictions.like("filearea", key,MatchMode.ANYWHERE)))))).list(); session.close(); return list;