I tried the following.
My tables are like :
Code:
SQL> desc my_one;
Name Null? Type
----------------------------------------- -------- ---------------
MY_ID NOT NULL NUMBER(19)
TWO_ID NUMBER(19)
NAME VARCHAR2(255)
SQL> desc my_two;
Name Null? Type
----------------------------------------- -------- ---------------
MY_ID NOT NULL NUMBER(19)
NAME VARCHAR2(255)
My code is as :
Code:
package tavant.platform.persistence.hibernate.cascade;
public class One
{
private long id;
private String name;
private Two two;
// ... getters and setters for those properties
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="tavant.platform.persistence.hibernate.cascade">
<class name="One" table="MY_ONE">
<id name="id" column="MY_ID" type="long">
<generator class="native"/>
</id>
<many-to-one name="two" class="Two"
cascade="all" outer-join="auto" column="TWO_ID"/>
<property name="name" column="NAME"/>
</class>
</hibernate-mapping>
Code:
package tavant.platform.persistence.hibernate.cascade;
public class Two
{
private long id;
private String name;
// ... getters and setters
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping package="tavant.platform.persistence.hibernate.cascade">
<class name="Two" table="MY_TWO">
<id name="id" column="MY_ID" type="long">
<generator class="native"/>
</id>
<property name="name" column="NAME"/>
</class>
</hibernate-mapping>
I inserted a row into MY_TWO table as :
Code:
SQL> insert into my_two(my_id, name) values(1, 'Hello Two');
And then, I tried the following code :
Code:
package tavant.platform.persistence.hibernate.cascade;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
public class Test
{
public static void main(String[] args) throws Exception
{
SessionFactory sessions = new Configuration()
.addClass(One.class)
.addClass(Two.class)
.buildSessionFactory();
Session session = sessions.openSession();
Transaction transaction = session.beginTransaction();
One one = new One();
one.setName("One 1");
Two two = new Two();
two.setName("Two 2");
two.setId(1); // a DB row with ID 1 already exists.
one.setTwo(two);
session.save(one);
transaction.commit();
session.close();
System.out.println("Saved ONE");
}
}
It worked fine for me. I use Hibernate 2.1.4 on Oracle 8i. Please try it.