可以使用where子句來限定查詢的條件,除了 = 運算之外,還有 >、>=、<、<=、!= 或 <>等比較運算,例如:
Session
session = sessionFactory.openSession();
Query query = session.createQuery("from User user where user.name='caterpillar'");
List names = query.list();
Iterator iterator = names.iterator();
while(iterator.hasNext()) {
User user = (User) iterator.next();
System.out.println(user.getAge() + "\t" + user.getName());
}
Query query = session.createQuery("from User user where user.name='caterpillar'");
List names = query.list();
Iterator iterator = names.iterator();
while(iterator.hasNext()) {
User user = (User) iterator.next();
System.out.println(user.getAge() + "\t" + user.getName());
}
也可以在where子句上進行運算式,例如:
Query
query = session.createQuery("from User user where (user.age / 10 = 3)");
也可以在where子句上使用and、or,例如:
Query
query = session.createQuery("from User user where (user.age >
20) and (user.name = 'caterpillar')");
is not nullL與is null則可以測試欄位值是否為空值,例如:
Query
query = session.createQuery("from User user where user.name is not
null");
between可以測試欄位值是否在指定的範圍之內,例如:
Query
query = session.createQuery("from User user where user.age between 20
and 30");
可以使用in或not in來測試欄位值是否在您指定的集合中,例如:
Query
query = session.createQuery("from User user where user.name
in('caterpillar', 'momor')");
like或not like可以讓您進行模糊條件搜尋,例如想搜尋名稱中含有cater開頭的資料:
Query query =
session.createQuery("from User user where user.name like 'cater%'");
可以對查詢結果使用order by進行排序:
Query
query = session.createQuery("from User user order by user.age");
可使用desc反排序:
Query
query = session.createQuery("from User user order by user.age desc");
可同時指定兩個以上的排序方式,例如先按照"age"反序排列,如果"age"相同,則按照"name"順序排列:
Query
query = session.createQuery("from User user order by user.age desc,
user.name");
可以配合GROUP BY子句,自動將指定的欄位依相同的內容群組,例如依欄位"sex"分組並作平均:
Query
query = session.createQuery("select user.sex, avg(user.age) from User
user group by user.sex");
一個執行的結果如下:
+-------------------------------+ | sex | avg(age) | +-------------------------------+ | male | 30 | +-------------------------------+ | female | 25 | +-------------------------------+ |