不迫切一行一个数组
d1只创建一次
封装成数组装进List
类+关联属性,而不是类了。
public List find(String hql) {
return HibernateSessionFactory.getSession()
.createQuery(hql)
.list();
}
package biz;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import dao.DeptDAO;
import dao.HibernateSessionFactory;
import entity.Dept;
public class DeptBiz {
private DeptDAO dao = new DeptDAO();
public void findTest() {
Transaction tx = null;
Dept dept = null;
try {
tx = HibernateSessionFactory.getSession().beginTransaction();
/*
* select * from Dept d left join Emp e on d.deptno = e.deptno where
* ...
*/
// String hql = "from Dept d left join Emp e";
String hql = "from Dept d left join d.emps e order by d.deptno";// 省略以上的
List<Object[]> result = dao.find(hql);
//不迫切查出来封装成数组对象 然后放进List中
// fetch迫切查出结果集是一样的,主要是封装不一样。
for (Object[] row : result) {
System.out.println(row[0]+"\t"+row[1]);
}
tx.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tx != null) {
tx.rollback();
}
}
}
@Test
public void test5() {
DeptBiz biz = new DeptBiz();
biz.findTest();
}
迫切
package biz;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import dao.DeptDAO;
import dao.HibernateSessionFactory;
import entity.Dept;
public class DeptBiz {
private DeptDAO dao = new DeptDAO();
public void findTest() {
Transaction tx = null;
Dept dept = null;
try {
tx = HibernateSessionFactory.getSession().beginTransaction();
/*
* select * from Dept d left join Emp e on d.deptno = e.deptno where
* ...
*/
// String hql = "from Dept d left join Emp e";
String hql = "from Dept d left join fetch d.emps e order by d.deptno";// 省略以上的
List<Dept> result = dao.find(hql);
for (Dept dept1 : result) {
System.out.println(dept1.getDeptno() + "\t" + dept1.getDname()
+ "\t" + dept1.getEmps().size());
}
tx.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tx != null) {
tx.rollback();
}
}
}
没有右迫切
因为右是完整的表,封装时时以左边为准,你不可能让它去找null做对应吧~
// 根据部门名称 查出所有该部门的雇员
// 等值连接 select * from Dept d,Emp e where d.deptno=e.deptno;
hql = "select e from Emp e,Dept d where d=e.dept and d.dname= ?";
hql = "from Dept d,Emp e where d=e.dept";
hql = "from Dept d,Emp e where d.deptno=e.dept.deptno";
// WRONG!!
hql = "from Dept d,Emp e where d.emps=e";
// emps是一个集合,不可以等于一个对象(数据类型都不对!) set!=Emp
// 隐式内连接
hql = "from Emp e where e.dept.dname= :dname";
/*内连接
* select e.EMPNO,e.ENAME,d.DNAME
* from EMP e inner join DEPT d on e.DEPTNO = d.DEPTNO;
* where....
*/