2013-05-09 57 views
0

假设我有:Hibernate何时从FK创建一个新条目到非PK列?

-- table_1 ------------------- 
|id  | property_x | data | 
------------------------------ 

-- table_2 ------------------------ 
|id  | property_x | moar_data | 
----------------------------------- 

table_1有FK从property_xtable_2.property_x
(为什么不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> 

问题是我想要使用session.save(objTable1)保存对象Table1,而不在数据库中创建新的Table2条目,也不加载它。 我已经通过创建一个新对象完成了这项工作,并且只设置了主键值,其他所有内容都保留空白,并且不让它更新表格,但这不是PK> _ <。

现在,假设我有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); 
} 

...它创建了一个新的项目,我猜这是因为PK(ID)为Table2未设置。

我的问题是,hibernate如何决定从FK对象创建一个新的条目在数据库中?是否有办法避免在HBM文件上?

回答

0

这是级联的诠释,如果你不希望在数据库中创建表2,不要设置它为儿童,但如果你想要更新表2,你需要表2的ID。

或者,您可以在表1的hbm或级联=“更新”中设置cascade =“none”,但表2仍然不会更新,不带id。

+0

所以理想的方法是首先加载Table2对象,或者创建一个HQL语句? – Goodwine 2013-05-09 18:02:09

+0

是的,你应该使用table1外键加载table2,然后执行更新。 – Ziul 2013-05-09 19:08:51

+0

你说得对,或者是你自己做HQL语句,我会试试这个,希望它不会很慢(不得不加载一个我不会真正使用的对象),如果那是可以接受的,我会使用它,否则我会构建查询。 – Goodwine 2013-05-10 13:32:26