// 等值连接// 返回 Array[tuple2<Classes, Student>]String sql ="from Classes c, Student s where c.cid=s.classes.cid";
// 内连接, 放回结果和上面相同String sql ="from Classes c inner join c.students";
// 迫切内连接, return List<Classes>String sql ="from Classes c inner join fetch c.students";
// 左外连接, return Array[tuple2<Classes, Student>]String sql ="from Classes c left join c.students";
// 迫切左外连接, return List<Classes> String sql ="from Classes c left outer join fetch c.students";
// 迫切左外连接, 数据会重复, 用distinct 排重String sql ="select distinct c from Classes c left outer join fetch c.students";
// 迫切左外连接, return List<Student>String sql ="from Student s left outer fetch join s.classes";
// 多表条件查询, 隐式内连接Listlist= session.createQuery("from Order o where o.customer.name=?")
.setParameter(0, "mary");
// QBC 连接查询
Criteria criteria = session.createCriteria(Order.class);
// 设置别名, 表关联
criteria.createAlias("customer", "c");
// 在关联时, 使用左外连接
criteria.createAlias("customer", "c", Criteria.LEFT_JOIN);
criteria.add(Restrictions.eq("c.name", "mary"));
criteria.list();
// 投影查询, 同理也可以查询几个字段, 生成模型类, 带构造函数的查询, 不能带 fetchString sql ="from new io.zhooer.NewClasses(c.cname, s.sname) c left outer join c.students";
String sql ="from count(c) from Customer c";
// QBC方式Listlist= session.createCriteria(Customer.class)
.setProjection(
Projection.projectionList()
.add(Property.forName("name"))
.add(Property.forName("age"))
).list();
总结 :
如果页面上要显示的数据和数据库中的数据相差甚远, 利用带select的构造器进行查询
如果页面上要显示的数据和数据库中的数据相差不是很远, 用迫切连接
如果采用迫切连接, from 后面跟的那个对象就是结构主体
报表查询
1
2
Long count = (Long)session.createQuery("selectcount(*) from Customer");
List list = session.createQuery("selectcount(*) fromOrdergroupby customer").list();
命名查询和离线查询
1
2
3
4
5
6
7
<!-- hbm.xml --><queryname="sql1">
from Cusomer
</query><sql-queryname="sql2">
select * from cusomer
</sql-query>