//查詢指定列名的-----非持久態(tài)
//非持久化:因為查詢出的數(shù)據(jù)與數(shù)據(jù)庫不對應(yīng)
//s.sid,s.name指定的列名 別名.列名
String hql="select s.sid,s.name from Student s";
Query query=session.createQuery(hql);
//查詢出來的是一個object數(shù)組,不是一個學(xué)生對象
List<Object[]> list = query.list();
for (Object[] objects : list) {
System.out.println(objects[0] "\t" objects[1]);
}
指定列名查詢?nèi)浚ǔ志没瘮?shù)據(jù))
//查詢指定列名的-----持久態(tài)
//在數(shù)據(jù)庫有與之對應(yīng)的,在student對象中
//new Student(s.sid,s.name)-------在實體類中要與之對應(yīng)的構(gòu)造函數(shù)
String hql="select new Student(s.sid,name) from Student s";
Query query=session.createQuery(hql);
//查詢出的就是Student對象
List<Student> list=query.list();
for (Student student : list) {
System.out.println(student.getName());
}
函數(shù)查詢
//函數(shù)查詢---最大值
//max(別名.列名)
String hql="select max(s.sid) from Student s";
Query query=session.createQuery(hql);
//返回時是唯一的結(jié)果
int max=(Integer) query.uniqueResult();
System.out.println("最大值" max);
注:在查詢總行數(shù)的時候需要用long類型接收
占位符查詢
第一種 通過取占位符名 :自定義名
//:name 自定義的名稱
String hql="select s from Student s where s.name like :name";
//設(shè)置占位符的值 setParameter(占位符名(不需要:,賦值)); 沒有順序
Query query=session.createQuery(hql).setParameter("name", "%xx%");
List<Student> list = query.list();
for (Student student : list) {
System.out.println(student.getName());
}
第二種:通過?占位符
//hibernate版本在5.版本以上的要在?后面加占位符的順序
//比如 s.name like ?0 and s.age>?1
String hql="select s from Student s where s.name like ?0";
//賦值的時候就需要有順序 從0開始
Query query=session.createQuery(hql).setParameter(0, "%x%");
List<Student> list = query.list();
for (Student student : list) {
System.out.println(student.getName());
}
分頁查詢
//查詢出全部
String hql="select s from Student s ";
int pages=1;//當前的頁數(shù)
int pageSize=5;//一頁顯示多少行
//setMaxResults設(shè)置一頁顯示的最大數(shù) setFirstReault設(shè)置從哪一頁開始
Query query=session.createQuery(hql).setMaxResults(pageSize).setFirstResult((pages-1)*pageSize);
List<Student> list = query.list();
for (Student a : list) {
System.out.println(a.getName());
}
下面有連接查詢(我使用的是一對多的關(guān)系)
//連接查詢(全連接)
//c.province.pid c里面的province對象里面的pid與p對象里面的pid
String sql="select c from City c inner join Province p on c.province.pid=p.pid";
Query query = session.createQuery(sql);
List<City> list = query.list();
for (City c : list) {
System.out.println(c.getCname());
}
子連接
//查詢城市帶漢的所有省份名稱
String hql="select p from Province p where p.pid in(select c.province.pid from City c where c.cname like :cname)";
Query query = session.createQuery(hql).setParameter("cname", "%漢%");
List<Province> list=query.list();
for (Province province : list) {
System.out.println(province.getPname());
}
子連接2
//查詢城市帶湖的所有省份名稱-----一個表的查詢條件是另一個表的查詢的結(jié)果
String hql="select p from Province p where p.pid in(select c.province.pid from City c where c.cname like :cname)";
Query query = session.createQuery(hql).setParameter("cname", "%漢%");
List<Province> list=query.list();
for (Province province : list) {
System.out.println(province.getPname());
}