一个部门有多个员工,部门知道他有哪些员工,员工属于一个部门,他知道他的部门信息。
部门类中有一个集合属性set,用来保存他部门类的员工
private Set<Employee> employees = new HashSet<Employee>();
配置文件中配置怎么填充这个属性,相当于去Employee对应的表中查找deptid和自己相等的员工,把它加入到set中。
<set name="employees" cascade="save-update">
<key column ="deptid"/>
<one-to-many class="com.shizhan.po.Employee"/>
</set>
部门类:
package com.shizhan.po;
import java.util.HashSet;
import java.util.Set;
public class Deptment implements java.io.Serializable {
private Long deptid;
private String deptname;
//保存员工下的部门
private Set<Employee> employees = new HashSet<Employee>();
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
public Long getDeptid() {
return this.deptid;
}
public void setDeptid(Long deptid) {
this.deptid = deptid;
}
public String getDeptname() {
return this.deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
员工类:
package com.shizhan.po;
public class Employee implements java.io.Serializable {
private Long epno;
private Deptment deptment;
private String epname;
public Long getEpno() {
return this.epno;
}
public void setEpno(Long epno) {
this.epno = epno;
}
public Deptment getDeptment() {
return this.deptment;
}
public void setDeptment(Deptment deptment) {
this.deptment = deptment;
}
public String getEpname() {
return this.epname;
}
public void setEpname(String epname) {
this.epname = epname;
}
@Override
public String toString() {
return "Employee [epno=" + epno + ", deptment=" + deptment
+ ", epname=" + epname + "]";
}
}
部门xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.shizhan.po.Deptment" table="DEPTMENT" schema="SCOTT">
<id name="deptid" type="java.lang.Long">
<column name="DEPTID" precision="10" scale="0" />
<generator class="increment" />
</id>
<property name="deptname" type="java.lang.String">
<column name="DEPTNAME" length="20" />
</property>
<!-- 配置多的一端 -->
<set name="employees" cascade="save-update">
<key column ="deptid"/>
<one-to-many class="com.shizhan.po.Employee"/>
</set>
</class>
</hibernate-mapping>
员工xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.shizhan.po.Employee" table="EMPLOYEE" schema="SCOTT">
<id name="epno" type="java.lang.Long">
<column name="EPNO" precision="10" scale="0" />
<generator class="increment" />
</id>
<many-to-one name="deptment" class="com.shizhan.po.Deptment" fetch="select" cascade="save-update">
<column name="DEPTID" precision="10" scale="0" />
</many-to-one>
<property name="epname" type="java.lang.String">
<column name="EPNAME" length="20" />
</property>
</class>
</hibernate-mapping>