简体   繁体   中英

When does Hibernate create a new entry from a FK to a non-PK column?

suppose I have:

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

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

And that table_1 has a FK from property_x to table_2.property_x
(why not table_2.id ? IDK, this project was already like this :( )

The HBMs look like this:

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

and

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

The thing is that I want to save an object Table1 using session.save(objTable1) , without creating a new Table2 entry in the DB, and without loading it either. I have done this in the past by creating a new object, and only setting the primary key values, leaving everything else blank, and not letting it update the Table2 table, but this is not the PK >_<.

Now, suppose I have in table_2 an entry with id=5 , property_x="EX" . When I do the following...

// example method
public void saveSomething(Sessions sess) {
    Table1 table1 = new Table1();
    Table2 table2 = new Table2();

    table2.setPropertyX("EX");
    table1.setTable2(table2);

    sess.save(table1);
}

... it creates a new entry, I'm guessing it's because the PK (id) for Table2 is not set.

My question is, how does hibernate decide to create a new entry in the DB from a FK object?, and is there a way to avoid that on the HBM files?

It's the cascade anotation, if you dont want table 2 to be created in the db, dont set it as a child, but if you want table 2 to be updated, you need the table 2 id.

Alternatively, you can set cascade="none" in the hbm of table 1 or cascade="update", but table 2 still wont be updated without the id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM