TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
1,建立一个中间表:
联合主键,两列值,不能存在两列值同时相同的数据
体现多对多的关系
2,在java文件中创建:
Employee中: Set<Project> projects = new HashSet<Project>();
Project中:Set<Employee> employees = new HashSet<Employee>();
employee.hbm.xml中:
<set name="projects" table="r_emp_proj">
<key column="r_emp_id"></key>
<many-to-many class="com.zhangjie.hib.entity.manytomany.Project" column="r_proj_id"></many-to-many>
</set>
r_emp_proj表示中间表,r_emp_id对应Employee对象,r_proj_id对应表r_emp_proj中的列r_proj_id
project.hbm.xml中:
<set name="employees" table="r_emp_proj">
<key column="r_proj_id"></key>
<many-to-many class="com.zhangjie.hib.entity.manytomany.Employee" column="r_emp_id"></many-to-many>
</set>
3,查询代码:
/**
* 查询某个员工参加过的项目
*
*/
@Test
public void test1(){
Session session = HibernateSessionFactory.getSession();
Employee employee = (Employee)session.get(Employee.class, 1L);
Set<Project> projects = employee.getProjects();
System.out.println(employee.getEmployeeName()+"参加了项目:\n");
for(Project pro : projects){
System.out.println(pro.getProjectName());
}
session.close();
}
/**
* 查询某个项目参加的员工
*/
@Test
public void test2(){
Session session = HibernateSessionFactory.getSession();
Project project = (Project)session.get(Project.class, 1L);
Set<Employee> employees = project.getEmployees();
System.out.println("参加项目"+project.getProjectName()+"的员工有:\n");
for(Employee employee : employees){
System.out.println(employee.getEmployeeName());
}
}
|
|