返回一个结果查询
//注意事项。查询条件只能返回一个或者零个结果。超过则会报错
String hql = "From Dept d Where d.deptno > 9";
Query query = session.createQuery(hql);
Dept dept = (Dept)query.uniqueResult();
System.out.println(dept.getDeptno()+"\t"+dept.getDname()+"\t"+dept.getLoc());
}
//distinct关键字去除数组中相同的元素
String hql = "Select Distinct d.dname From Dept d";
Query query = session.createQuery(hql);
List<Object> list = query.list();
for (Object obj : list) {
System.out.println(obj);
}
@Test
public void queryAll() {
// String hql2 = "From Dept";
// String hql =
// "Select e.ename,e.comm,d.deptno,d.dname From Emp e,Dept d Where e.dept = d.deptno ";
// Query query = session.createQuery(hql);
// String hql = "Select d.deptno From Dept d";
// Dept d = new Dept();
// Query query = session.createQuery(hql);
// List<Dept> dept = new ArrayList<>();
// List<Object> list = query.list();
// // list.get(0) = i;
// for (Object obj : list) {
// int i = (int) obj;
// d = (Dept) session.get(Dept.class, i);
// System.out.println(i);
// dept.add(d);
// }
/*
- 通过Map查询
- map。get(“别名”)
*/
String hql = "Select new Map(e.ename as en,e.comm as cm,d.deptno as no) From Emp e,Dept d";
Query query = session.createQuery(hql);
List<Map> list = query.list();
for (Map map : list) {
System.out.println(map.get("en"));
System.out.println(map.get("cm"));
System.out.println(map.get("no"));
}
//session.close();
// 由于HQL是对映射类的操作,所以查询关联表它并不能返回数据库表,而是返回一个数组
// List<Object[]> list = query.list();
// for (Object[] obj : list) {
// System.out.println(obj[0]+"\t"+obj[1]+"\t"+obj[2]+"\t"+obj[3]);
// }
// for (int j = 0; j < dept.size(); j++) {
// for (Object obj : dept.get(j).getEmps()) {
// Emp e = (Emp) obj;
// System.out.println(e.getEname());
// }
// }
}