我是新来的冬眠。我必须表部门和老师。一个系可以有多名教师,但一名教师只能隶属于一个系。我有以下映射:
@Entity
@Table(name = "department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@OneToMany (cascade=CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "department_id")
private List<Teacher> teachers = new ArrayList<Teacher>();
}
和
@Entity
@Table(name = "teacher")
public class Teacher {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "fName")
private String fName;
@Column(name = "lName")
private String sName;
@Column(name = "degree")
private String degree;
@ManyToOne
private Department department;
}
还有 getter 和 setter,为简单起见,我省略了它们。我正在使用 MySql 数据库。当我尝试用新教师插入新部门时,一切正常。但是,我还希望能够获得分配给每个部门的教师的完整部门列表。目前在我的数据库中,我有 5 个部门和 13 位教师。但是当我执行以下代码时:
DepartmentDaoImpl ddi = new DepartmentDaoImpl();
List<Department> departments = ddi.getAllDepartment();
for (Department k : departments){
printDepartmentData(k);
List<Teacher> teachers = k.getTeachers();
for (Teacher t : teachers){
printTeacherName(t);
}
}
我的 getAllDepartments 实现:
@Override
public ArrayList getAllDepartment() throws SQLException {
Session session = null;
ArrayList<Department> result = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
result = (ArrayList)session.createCriteria(Department.class).list();
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(session != null && session.isOpen()){
session.close();
}
}
return result;
}
Sql 创建表:
CREATE TABLE teacher (
id INTEGER PRIMARY KEY auto_increment,
fName varchar(30),
lName VARCHAR(30),
degree VARCHAR(100),
department_id INTEGER
);
CREATE TABLE department(
id INTEGER PRIMARY KEY auto_increment,
name VARCHAR(100),
description VARCHAR(5000)
);
我得到了 13 个部门实例。我得到了第一部门的 5 个实例(我有 5 名教师分配给它)他们每个人都分配了相同的五名教师,第二部门的两个实例(我有两名教师分配给它)他们每个人都分配了两个相同的教师,所以在。有人可以弄清楚,如何解决它?我需要获得 5 个部门实例,以及
相应数量的教师。