我有一个员工类,它从证书类中隐藏了一个List。当我将员工类保存到数据库时,hibernate将插入repititive元素传递给数据库。以下是我的映射文件详细信息:
<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|
+------+--------------------+--------+--------------+
答案 0 :(得分: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)
和l.get(1)
是同一个对象(具有1个对象ID),但l.get(2)
和l.get(3)
是具有不同ID的不同对象,尽管具有相同的值。这个清单带来的对象只有3个,有4个不同的门。