views:

237

answers:

1

I have Country and State objects. I intend to have unidirectional many to one relationship from State to Country. I don't want to store any references to States in Country I have defined mapping as below. When I delete even one State object, all Countries are deleted!

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt;
<hibernate-mapping>
    <class
        name="places.Country" 
        table="COUNTRY"  
        dynamic-update="true">

        <!-- Technical ID -->
        <id name="name" type="string" unsaved-value="new" column="COUNTRY_NAME">
        </id>

        <!-- Properties -->
        <property name="commonName" 
            column="COMMON_NAME"
        />
        <property name="iso2Code" 
            column="ISO2_CODE"
        />
        <property name="iso3Code" 
            column="ISO3_CODE"
        />
        <property name="isoNumeric" 
            column="ISO_NUMERIC"
        />
        <property name="ituCode" 
            column="ITU_CODE"
        />
        <property name="ianaCode" 
            column="IANA_CODE"
        />
    </class>
    <class
        name="places.State" 
        table="STATE"  
        dynamic-update="true">

        <!-- Technical ID -->
        <id name="name" type="string" unsaved-value="new" column="STATE_NAME">
        </id>

        <!-- Properties -->
        <property name="code" column="STATE_CODE"
        />

    <many-to-one name="country" column="COUNTRY" not-null="true" cascade="none" 
        class="places.Country"
    />        
    </class>

</hibernate-mapping>
+1  A: 

The provided mapping looks fine. Actually, executing the following code using exactly your mapping:

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();

State aState = (State) session.load(State.class, stateId);
session.delete(aState);

session.getTransaction().commit();

Generates the following output:

...
Hibernate: select state0_.STATE_NAME as STATE1_1_0_, state0_.STATE_CODE as STATE2_1_0_, state0_.COUNTRY as COUNTRY1_0_ from STATE state0_ where state0_.STATE_NAME=?
Hibernate: delete from STATE where STATE_NAME=?
3270 [main] INFO org.hibernate.impl.SessionFactoryImpl - closing

Things are working as expected, my countries are still there.

Maybe show some code?

Pascal Thivent
Pascal, thanks a lot!
Prashant