我有部门和员工实体,我想将它们映射为一对多。
如何在XML映射中使用List而不是Set?我在Internet上找到了这段代码,但是当执行"from Department"
时,错误是"Repeat property department_id in Employee.department"
,但是如果我删除了部门中的<index>
,它就会
是"Unable to read XML"
。
Department.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 2, 2015 7:14:52 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="emp.entity.Department" table="department" schema="dbo" catalog="Emp" optimistic-lock="version">
<id name="departmentId" type="long">
<column name="department_id" />
<generator class="assigned" />
</id>
<property name="deptName" type="string">
<column name="dept_name" length="50" not-null="true" />
</property>
<list name="employees" table="Employee" inverse="true" cascade="all" >
<key>
<column name="department_id" />
</key>
<index column="department_id"></index>
<one-to-many class="emp.entity.Employee" />
</list>
</class>
</hibernate-mapping>
Employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Aug 2, 2015 7:14:52 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="emp.entity.Employee" table="Employee" schema="dbo" catalog="Emp" optimistic-lock="version">
<id name="employeeId" type="int">
<column name="employee_id" />
<generator class="assigned" />
</id>
<many-to-one name="department" class="emp.entity.Department" fetch="select">
<column name="department_id" />
</many-to-one>
<property name="firstname" type="serializable">
<column name="firstname" />
</property>
</class>
</hibernate-mapping>
答案 0 :(得分:1)
如上所述,列表中的子项标识符和子项索引必须有两列不同,因此列表定义应为:
<list name="employees" inverse="true" cascade="all" >
<key>
<column name="department_id" />
</key>
<index column="other_column_to_keep_the_order_of_the_element_in_the_list"></index>
<one-to-many class="emp.entity.Employee" />
</list>
如果您只需要将元素放在列表中而不需要将其订单保存在数据库中,则可以声明<bag>
而不是<list>
。