Hibernate mapping to object that already exists

Posted by teehoo on Stack Overflow See other posts from Stack Overflow or by teehoo
Published on 2010-05-02T23:36:20Z Indexed on 2010/05/02 23:58 UTC
Read the original article Hit count: 284

Filed under:
|
|
|

I have two classes, ServiceType and ServiceRequest. Every ServiceRequest must specify what kind of ServiceType it is. All ServiceType's are predefined in the database, and ServiceRequest is created at runtime by the client.

Here are my .hbm files:

<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>

and

<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>

When I run this, I get

com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

I think my problem is that when I create a new ServiceRequest object, ServiceType is one of its properties, and therefore when I'm saving ServiceRequest to the database, Hibernate attempts to insert the ServiceType object once again, and finds that it is already exists. If this is the case, how do I make it so that Hibernate points to the exists ServiceType instead of trying to insert it again?

© Stack Overflow or respective owner

Related posts about hibernate

Related posts about foreign