我在MySQL数据库的桥表中有四条记录。在hibernate中使用@ManyToMany,我得到了员工的准确订单,但错误的项目不正确。以下是确定我在哪里犯错的必要材料。
这是来源。
@Entity
@Table(name="PROJECT")
public class ProjectBean {
@Id @GeneratedValue @Column(name="PROJECT_ID")
private int projectId;
@Column(name="TITLE")
private String projectTitle;
@ManyToMany(mappedBy="projects")
private Collection<EmployeeBean> employees;
public ProjectBean() {
employees = new ArrayList<EmployeeBean>();
}
//getters & setters
}
@Entity
@Table(name="EMPLOYEE")
public class EmployeeBean {
@Id @GeneratedValue @Column(name="EMPLOYEE_ID")
private int employee_id;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@ManyToMany
@JoinTable(name="EMPLOYEE_PROJECT",joinColumns=@JoinColumn(name="EMPLOYEE_ID"),inverseJoinColumns=@JoinColumn(name="PROJECT_ID"))
private Collection<ProjectBean> projects;
public EmployeeBean() {
projects = new ArrayList<ProjectBean>();
}
//getters and setters goes here
}
最后跟随的是Main Class,我试图以与我们在最顶层图像中看到的顺序相同的方式遍历列表。
ArrayList<ProjectBean> projects = (ArrayList<ProjectBean>)session.createQuery("SELECT projects FROM EmployeeBean").list();
ArrayList<EmployeeBean> employees = (ArrayList<EmployeeBean>)session.createQuery("SELECT employees FROM ProjectBean").list();
System.out.println("EmpID\tPrjID");
int i = 0;
for (EmployeeBean employeeBean : employees) {
System.out.print(employeeBean + "\t");
ProjectBean projectBean = (ProjectBean) projects.get(i);
i++;
System.out.println(projectBean);
}
答案 0 :(得分:1)
你的代码真的没有意义。您遍历员工,并且对于员工列表中索引为i
的每个员工,您将在项目列表的索引i
处打印项目。
如果要显示每个员工的所有项目,则需要一个查询和两个嵌套循环:
List<EmployeeBean> employees = session.createQuery("SELECT e FROM EmployeeBean e").list();
for (EmployeeBean employee : employees) {
System.out.println(employee);
for (Project project : employee.getProjects()) {
System.out.println("\t" + employee);
}
}
另外,请注意我没有通过查询将列表返回到ArrayList:这是完全没用的,并且只是因为Hibernate碰巧返回一个ArrayList。它可以选择返回任何其他List实例,并且您的代码会中断。接口程序。