简体   繁体   English

Hibernate以一对多的关系检索错误的对象列表

[英]Hibernate retrieve wrong list of objects in one-to-many relation

I'm new to hibernate. 我刚接触休眠。 I have to tables Department and Teacher. 我要表部门和老师。 One Department can have many teachers, but one teacher can be attached to only one department. 一个部门可以有很多教师,但一个教师只能隶属于一个部门。 I have the following mapping: 我有以下映射:

@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>();
}

and

@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;
}

also there are getters and setters, which I omitted for simplicity. 还有吸气剂和固定剂,为简单起见,我省略了它们。 I'm using MySql database. 我正在使用MySql数据库。 When I trying to insert new department with new teachers, everything works fine. 当我试图用新老师插入新部门时,一切正常。 But, also I want be able to get a full list of departments with teachers, assigned to each department. 但是,我也希望能够获得一个完整的教师部门列表,分配给每个部门。 Currently in my database i have 5 departments and 13 teachers. 目前在我的数据库中我有5个部门和13个教师。 But when I executing following code: 但是当我执行以下代码时:

    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);
        }
    }

And my getAllDepartments implementation: 我的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 to create tables: 用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) 
);

I get 13 instances of department. 我得到了13个部门的实例。 And I get 5 instances of first department (I have 5 teachers assigned to it) each of them have same five teacher assigned, two instances of second department (I have two teachers assigned to it) each of them have two same teachers assigned and so on. 我得到了第一个部门的5个实例(我有5个教师分配给它)每个人都分配了相同的五个教师,第二个部门的两个实例(我有两个教师分配给它)每个部门都有两个相同的教师分配,所以上。 Can someone figure out, how to fix it? 有人可以弄清楚,如何解决它? I need to get 5 instances of department, with 我需要获得5个部门实例
corresponding number of teachers. 相应的教师人数。

Since you configure the one to many relationship with fetch = FetchType.EAGER , hibernate performs a join on the two tables. 由于您使用fetch = FetchType.EAGER配置一对多关系,因此hibernate会对两个表执行连接。 The result you see is caused by this join. 您看到的结果是由此连接引起的。

Make sure that you have correct equals() and hashCode() methods in both Department and Teacher . 确保在DepartmentTeacher都有正确的equals()hashCode()方法。 If this does not solve the problem, try to use a Set instead of a List . 如果这不能解决问题,请尝试使用Set而不是List

Do the below change and test it 做以下更改并测试它

   @OneToMany (cascade=CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="department")
    private List<Teacher> teachers = new ArrayList<Teacher>();

try change to this : 尝试改变这个:

@OneToMany (mappedBy="department", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Teacher> teachers = new HashSet<Teacher>();

and change that: 并改变:

@ManyToOne
private Department department;

to : 至 :

@Collumn(name = "department")
private Integer department;

just try this in your dao, it will help 只需在你的dao中尝试这个,它会有所帮助

result = (ArrayList) session.createCriteria (Department.class). result =(ArrayList)session.createCriteria(Department.class)。 setResultTransformer (Criteria.DISTINCT_ROOT_ENTITY).list(); setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM