我有兩個類,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保存到數據庫時,Hibernat e嘗試再次插入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";
您正在運行的導致該異常的代碼是什麼? – oedo 2010-05-02 23:46:51
當我嘗試保存ServiceRequest時發生。它只是一個簡單的session.beginTransaction(); session.save(sr); session.getTransaction()。commit(); – 2010-05-02 23:52:01