自关联:本质还是原来双向一对多,原来要配置两个类,现在全部都配置在一个类里面
Employee
public class Employee {
private Long id;
private String name;
// 多对一: 多个员工对一上级
private Employee manager;
// 一对多:一个领导有多个下级
private Set<Employee> children = new HashSet<Employee>();
Employee.hbm.xml
<class name="Employee" table="t_employee">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<!-- private Employee manager;// 多对一: 多个员工对一上级 -->
<many-to-one name="manager" column="manager_id" class="Employee"/>
<!-- private Set<Employee> children = new HashSet<Employee>();// 一对多:一个领导有多个下级 -->
<set name="children" inverse="true" cascade="save-update">
<key column="manager_id" />
<one-to-many class="Employee" />
</set>
</class>
MainTest
public class MainTest {
Session session = null;
@Before
public void save() {
session = HibernateUtils.INSTANCE.getSession();
session.beginTransaction();
Employee boss = new Employee("boss");
Employee manager = new Employee("manager");
Employee emp1 = new Employee("emp1");
Employee emp2 = new Employee("emp2");
manager.addEmployee(emp1).addEmployee(emp2);
boss.addEmployee(manager);
session.save(boss);
}
@Test
public void get() {
Employee boss = (Employee) session.get(Employee.class, 1L);
System.out.println("boss:" + boss.getName());
Set<Employee> employees = boss.getChildren();
for (Employee manager : employees) {
System.out.println("manager:" + manager.getName());
Set<Employee> children = manager.getChildren();
for (Employee employee : children) {
System.out.println("employee:" + employee.getName());
}
}
}
@After
public void colse() {
session.getTransaction().commit();
session.close();
}
}
源码地址
https://github.com/je-ge/hibernate
如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!