Session session = HibernateSessionFactory.getSession();
/##
# 經過HQL語句查詢表中的sex字段,distinct是不容許有重複值
# ---給表中增長SEX字段後必須在xml映射文件以及實體類種增長屬性
# SQL="select distinct sex from admin";
#/
/#String hql = "select distinct a.sex from Admin as a ";
Query query = session.createQuery(hql);
List list = query.list();
Iterator iter = list.iterator();
while(iter.hasNext()){
//它不是一個對象,因此只許迭代打印出集合的數據
System.out.println(iter.next());
}#/
/##
# Count查詢所有的記錄數據
# SQL="select count(#) from admin";
#
#/
/##
#
avg查詢所有年齡的平均數,注意只能求int型的參數
# SQL="select avg(age) from admin";
# HQL="select avg(a.age) from Admin as a";
#/
/#String hql = "select count(#) from Admin as a";
Query query = session.createQuery(hql);
List list = query.list();
Iterator iter = list.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
}#/
/##
# 帶where 條件的HQL
# 更新刪除 HQL
# update Admin set name="李四" where aid="6"
# delete Admin where name="李四";
#
1.HQL="from Admin a where(a.age/10=3)";
#
2.HQL="from Admin a where(a.age>20) and (a.aname='趙六')"
#
3.is null或者is not null判斷數據是否爲空
#
HQL="from Admin a where a.name is not null";
#
4.between and 測試字段是否在指定的範圍內
#
HQL="from Admin a where a.aid between 5 and 9";
#
5.in或者not in來測試字段是否在指定的集合中
#
HQL="from Admin a where a.name in('張三','李四')"
#
6.like或者not like進行模糊條件查詢
#
HQL="from Admin a where a.name like'張%'";
#
7.order by 進行排序
#
HQL="from Admin a order by a.age";
#
8.desc 反排序
#
HQL = "from Admin a order by a.age desc";
#
9.同時指定兩個以上的排列方式,先按age反排序,如age相同再按name順序排列
#
HQL="from Admin a order by a.age desc,a.aname";
#
10.按指定的字段依據相同的內容分組,取出性別爲男或者女的平均年齡
#
HQL="select a.sex,avg(a.age) from Admin a group by a.sex";
#
11.只將平均大於20的數據分組顯示出來
#
HQL="select a.sex,avg(a.age) from Admin a group by a.sex" having avg(a.age)>20;
#
#/
String hql = "from Admin as a where a.aname=?";
Query query = session.createQuery(hql);
query.setString(0, "錢七");
List list = query.list();
Iterator iter = list.iterator();
while(iter.hasNext()){
Admin admin = (Admin) iter.next();
System.out.println(admin.getAname());
}
/##
# 分頁操做
#setFirstResult從第幾行開始取數據
#setMaxResults取多少行數據
#/
String sql = "from Admin as a";
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(3);
List l = q.list();
Iterator i = l.iterator();
while(i.hasNext()){
Admin a = (Admin)i.next();
System.out.println(a.getAname()+"--"+a.getSex()+"--"+a.getAge());
}
}