0

我有一个包含证书类列表的员工类。当我将员工类保存到数据库时,休眠将重复元素插入数据库。以下是我的映射文件详细信息:

<hibernate-mapping package="ir.imrasta.hibernate.sample4">
<class name="Employee" table="employee">
    <meta attribute="class-description">
        This class contains employee detail.
    </meta>
    <id name="id" type="int" column="id" >
        <generator class="native" />
    </id>
    <list name="certificates" cascade="all"  lazy="false">
        <key column="employee_id" />
        <list-index column="idx" />
        <one-to-many class="Certificate"/>
    </list>
    <property name="firstName" type="string" column="first_name" />
    <property name="lastName" type="string" column="last_name" />
    <property name="salary" type="int" column="salary" />
</class>

<class name="Certificate" table="list_certificate">
    <meta attribute="class-description">
        This class contains certificate records.
    </meta>
    <id name="id" type="int" column="id" >
        <generator class="native" />
    </id>
    <property name="name" type="string" column="certificate_name" />
</class>

我使用以下代码将 Employee 对象添加到数据库:

ManageEmployee me=new ManageEmployee();
List<Certificate> lst1=new ArrayList<Certificate>();
lst1.add(new Certificate("MCA"));
Certificate a=new Certificate("MBA");
lst1.add(a);
lst1.add(new Certificate("PMP"));
lst1.add(a);
int id1=me.addEmployee(new Employee("Ali","Habibi",200,lst1));  

但是当我在证书表中选择查询时,我得到以下结果:

+------+--------------------+--------+--------------+  
|  id  | certificate_name   |  idx   | employee_id  |  
+------+--------------------+--------+--------------+  
|  81  | MCA                |       1|           164|  
+------+--------------------+--------+--------------+  
|  82  | MBA                |       4|           164|  
+------+--------------------+--------+--------------+  
|  83  | PMP                |       3|           164|  
+------+--------------------+--------+--------------+  
4

1 回答 1

3

那是因为您使用相同的对象添加了多次,如下所示:

Certificate a=new Certificate("MBA");
lst1.add(a);
lst1.add(new Certificate("PMP"));
lst1.add(a);

如果您希望 MBA 被添加 2 次,您需要像这样插入它:

lst1.add(new Certificate("MBA"));
lst1.add(new Certificate("PMP"));
lst1.add(new Certificate("MBA"));

当您将相同的值保存到列表时:

List l = new ArrayList();
Integer a = new Integer(1);
l.add(a);
l.add(a);
l.add(new Integer(1));
l.add(new Integer(1));

l.get(0)andl.get(1)是同一个对象(有 1 个对象 id),但是l.get(2)andl.get(3)是一个不同的对象,虽然具有相同的值,但具有不同的 id。这份清单带来的物品只有3个,有4个不同的门。

于 2013-08-04T06:53:06.780 回答