假设我有:
-- table_1 -------------------
|id | property_x | data |
------------------------------
-- table_2 ------------------------
|id | property_x | moar_data |
-----------------------------------
并且table_1
具有从property_x
到table_2.property_x
的FK
(为什么不是table_2.id
?IDK,这个项目已经是这样了:()
HBMs是这样的:
<!-- Table 1 -->
<hibernate-mapping package="com.example">
<class name="Table1" table="table_1">
<id column="id" type="integer" name="id">
<generator class="native"/>
</id>
<many-to-one class="Table2" fetch="join" name="table2" not-null="false">
<column name="property_x" />
</many-to-one>
</class>
</hibernate-mapping>
和
<!-- Table 2 -->
<hibernate-mapping package="com.example">
<class name="Table2" table="table_2">
<id column="id" type="integer" name="id">
<generator class="native"/>
</id>
<property column="property_x" name="propertyX" type="string"/>
</class>
</hibernate-mapping>
事情是,我想保存一个对象Table1
使用session.save(objTable1)
,而不是在DB中创建一个新的表2条目,也没有加载它。在过去,我通过创建一个新对象,只设置主键值,将其他所有内容留空,并且不让它更新Table2
表来做到这一点,但这不是PK>_<</p>
。现在,假设我在table_2
中有一个条目with id=5
, property_x="EX"
。当我执行以下操作时…
// example method
public void saveSomething(Sessions sess) {
Table1 table1 = new Table1();
Table2 table2 = new Table2();
table2.setPropertyX("EX");
table1.setTable2(table2);
sess.save(table1);
}
…它创建了一个新条目,我猜这是因为Table2
的PK (id)没有设置。
我的问题是,hibernate如何决定从FK对象在DB中创建一个新条目?,有没有办法在HBM文件上避免这种情况?
这是级联注释,如果你不想在db中创建表2,不要将其设置为子,但如果你想要更新表2,你需要表2 id。
或者,您可以在表1的hbm中设置cascade="none"或cascade="update",但是如果没有id,表2仍然不会更新。