首页 > 代码库 > 关于hibernate的一点心得

关于hibernate的一点心得

1.部门和员工的关系:

部门<->员工是一对多的关系,即一个部门有多个员工,所以员工表里有部门id:depart_id

在下面这个代码中各添加部门和员工的一个记录即:新增一个部门,同时这个部门下有一个员工

static Department add() {
Session s = null;
Transaction tx = null;
try {
Department depart = new Department();
depart.setName("depart name");

Employee emp = new Employee();
emp.setDepart(depart);// 对象模型,建立两个对象之间的关联
emp.setName("emp name");

s = HibernateUtil.getSession();
tx = s.beginTransaction();
s.save(depart);//********************
s.save(emp);//*******************
tx.commit();
return depart;
} finally {
if (s != null) {
s.close();
}
}
}

注意:打*********号的两行顺序不变的话,控制台输出结果为:

Hibernate: insert into Department (name) values (?)
Hibernate: insert into Employee (name, depart_id) values (?, ?)

如果改变的话为:

Hibernate: insert into Employee (name, depart_id) values (?, ?)
Hibernate: insert into Department (name) values (?)
Hibernate: update Employee set name=?, depart_id=? where id=?

注意区别。。。。

 

2 .关于try catch finally 之间的那点事

碰到需要返回值的,如果没有catch,只有finally的话只需在try中return下就行了,不会报错

static Employee query(int empId) {
Session s = null;
Transaction tx = null;
try {
s = HibernateUtil.getSession();
tx = s.beginTransaction();
Employee emp = (Employee) s.get(Employee.class, empId);
tx.commit();
return emp;

} finally {
if (s != null) {
s.close();
}
}
}

如果有catch那么就需要在finally之后return,不然报错

static Employee query(int empId) {
Session s = null;
Transaction tx = null;
try {
s = HibernateUtil.getSession();
tx = s.beginTransaction();
Employee emp = (Employee) s.get(Employee.class, empId);
tx.commit();
return emp;

}

} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}finally {
if (s != null) {
s.close();
}
}

return null;
}