我有两个类,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