我在网上查了很多帖子,都没有解决我的问题。如果有人能提供帮助,真的很感激!我有 OneToMany 父子关系。当子复合键之一是父级 (Level1) 的外键时,Hibernate 不会级联插入子级 (Level2)。我指定了 cascade="all" ,无论逆是真还是假,结果都是一样的。也不例外,它根本不插入。下面的打印输出显示 Level1 已成功插入,但仅选择了 Level2,没有插入。
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=?
API 是 Hibernate 4.1.6/Spring 3.1.2。
这是 mySQL 的表定义:
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
);
这是测试代码。
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);
}
}
Level1的映射:
<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>
Level2的映射:
<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>