I have checked many posts on the internet and none address my problem. Really appreciate if anyone can help!
Hibernate does not cascade insert child (Level2) when one of the child composite keys is the foreign key to the parent (Level1). I specified cascade="all" and no matter the inverse is true or false, the results are the same. There is no exception, and it simply does not insert. Below print out shows Level1 was inserted successfully but Level2 was only selected, no insert.
Hibernate: insert into sst.level_1 (STATUS, NAME) values (?, ?)
Hibernate: select level2x_.LEVEL_1_ID, level2x_.TIMESEGMENT, level2x_.CATEGORY as CATEGORY4_ from sst.level_2 level2x_ where level2x_.LEVEL_1_ID=? and level2x_.TIMESEGMENT=?
The APIs are Hibernate 4.1.6/Spring 3.1.2.
Here is the table definition for mySQL:
Code:
CREATE TABLE level_1
(
ID int NOT NULL PRIMARY KEY AUTO_INCREMENT,
STATUS int,
NAME varchar(255)
);
CREATE TABLE level_2
(
LEVEL_1_ID int,
TIMESEGMENT int,
CATEGORY varchar(2),
PRIMARY KEY (LEVEL_1_ID, TIMESEGMENT),
FOREIGN KEY (LEVEL_1_ID) REFERENCES level_1(ID) ON DELETE CASCADE
);
Here is the test code.
Code:
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
doInsert(context);
}
private static void doInsert(ApplicationContext context) {
Level1 level1 = new Level1();
Level2 level2 = new Level2();
level1.setName("LEVEL 1 NAME");
level1.setStatus(1);
level1.getLevel2s().add(level2);
level2.setLevel1(level1);
level2.setCategory("CA");
level2.setId(new Level2Id(level1.getId(), 10));
Level1DAO level1DAO = (Level1DAO) context.getBean("Level1DAO");
level1DAO.save(level1);
}
}
Mapping for Level1:
Code:
<hibernate-mapping>
<class name="com.jc.hibernate.Level1" table="level_1" catalog="sst">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="identity" />
</id>
<property name="status" type="java.lang.Integer">
<column name="STATUS" />
</property>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<set name="level2s" inverse="true" cascade="all">
<key>
<column name="LEVEL_1_ID" not-null="true" />
</key>
<one-to-many class="com.jc.hibernate.Level2" />
</set>
</class>
</hibernate-mapping>
Mapping for Level2:
Code:
<hibernate-mapping>
<class name="com.jc.hibernate.Level2" table="level_2" catalog="sst">
<composite-id name="id" class="com.jc.hibernate.Level2Id">
<key-property name="level1Id" type="java.lang.Integer">
<column name="LEVEL_1_ID" />
</key-property>
<key-property name="timesegment" type="java.lang.Integer">
<column name="TIMESEGMENT" />
</key-property>
</composite-id>
<many-to-one name="level1" class="com.jc.hibernate.Level1" update="false" insert="false" fetch="select">
<column name="LEVEL_1_ID" not-null="true" />
</many-to-one>
<property name="category" type="java.lang.String">
<column name="CATEGORY" length="2" />
</property>
</class>
</hibernate-mapping>