【发布时间】:2011-02-14 21:00:39
【问题描述】:
我有两个类,ServiceType 和 ServiceRequest。每个 ServiceRequest 都必须指定它是什么类型的 ServiceType。所有 ServiceType 都在数据库中预定义,ServiceRequest 由客户端在运行时创建。
这是我的 .hbm 文件:
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false" mutable="true" name="xxx.model.entity.ServiceRequest" optimistic-lock="version" polymorphism="implicit" select-before-update="false">
<id column="USER_ID" name="id">
<generator class="native"/>
</id>
<property name="quantity">
<column name="quantity" not-null="true"/>
</property>
<many-to-one cascade="all" class="xxx.model.entity.ServiceType" column="service_type" name="serviceType" not-null="false" unique="false"/>
</class>
</hibernate-mapping>
和
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false" mutable="true" name="xxx.model.entity.ServiceType" optimistic-lock="version" polymorphism="implicit" select-before-update="false">
<id column="USER_ID" name="id">
<generator class="native"/>
</id>
<property name="description">
<column name="description" not-null="false"/>
</property>
<property name="cost">
<column name="cost" not-null="true"/>
</property>
<property name="enabled">
<column name="enabled" not-null="true"/>
</property>
</class>
</hibernate-mapping>
当我运行它时,我得到了
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
我认为我的问题是,当我创建一个新的 ServiceRequest 对象时,ServiceType 是它的属性之一,因此当我将 ServiceRequest 保存到数据库时,Hibernate 尝试再次插入 ServiceType 对象,并发现它已经存在。如果是这种情况,我该如何让 Hibernate 指向存在的 ServiceType 而不是尝试再次插入它?
抛出错误的代码:
/* Get existing Service Type from database */
ServiceType st = DAOFactory.getDAOFactory().getServiceTypeDAO().getServiceType(newServiceTypeName);
/* Set the ServiceType of the new Service Request*/
newServiceRequest.setServiceType(st);
/* Error occurs inside this function which simply calls
session.beginTransaction();
session.save(sr);
session.getTransaction().commit(); */
DAOFactory.getDAOFactory().getServiceRequestDAO().saveData(newServiceRequest);
return "newRequestDone";
【问题讨论】:
-
您正在运行的导致该异常的代码是什么?
-
当我尝试保存 ServiceRequest 时会发生这种情况。它只是一个简单的 session.beginTransaction(); session.save(sr); session.getTransaction().commit();
标签: hibernate mapping foreign-keys