0

私が持っているとします:

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

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

そして、それはからへtable_1のFKを持っています (なぜIDKではないのですか?このプロジェクトはすでにこのようなものでした:()property_xtable_2.property_x
table_2.id

HBM は次のようになります。

<!-- 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>

問題は、DB に新しい Table2 エントリを作成したり、ロードしたりせずに、 をTable1使用してオブジェクトを保存したいということです。session.save(objTable1)私は過去に新しいオブジェクトを作成し、主キーの値のみを設定し、他のすべてを空白のままにし、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 オブジェクトから DB に新しいエントリを作成することをどのように決定するかということです.HBM ファイルでそれを回避する方法はありますか?

4

1 に答える 1

0

これはカスケード注釈です。テーブル 2 をデータベースに作成したくない場合は子として設定しないでください。テーブル 2 を更新したい場合は、テーブル 2 の ID が必要です。

または、テーブル 1 の hbm で cascade="none" を設定するか、cascade="update" を設定できますが、テーブル 2 は ID なしでは更新されません。

于 2013-05-09T17:43:59.637 に答える