CharlesC
CharlesC

Reputation: 1410

Hibernate save is doing update

Here I'm working on a project that need insert an new audit record to a table. (e.g. new_vale vs old_value),with couple fields that need be updated.

Problem I'm tryint to solve:

the session.save() is not perform "INSERT" but instead it is perform "UPDATE".

    private void updateCollabPoApprovaForASN(CollabPoApprovalKey key, PurchaseOrderUpdateASN updateAsn){
       CollabPoApproval collabPoApproval  = this.collabPoApprovalGateway.findById(key);

       compareAndSetChangedValue(updateAsn, collabPoApproval);
       key.setChangeId(generateId());
       collabPoApproval.setKey(key);

       this.collabPoApprovalGateway.save(collabPoApproval);

}

Basically, what I did is, I use hibernate query to grab back the existing record , then I modify the primary key by manually set the ID and I update those couple audit fields. At last, save it back to the DB.

SQL Generated:

update CollabPoApproval set OLD_DRAWING_NUMBER=?, NEW_DRAWING_NUMBER=? ... where ID=? and SU_ID=? and PO=? and LINE=?

Background of the table:

The ID is not auto-increment field, it is a manually generated ID, basically it is a combination of TimeStamp+[0-999] (e.g. 20150412113637011), so I have to manually set it before I save it.
The table's primary key is a combination of 4 fields including the ID and they are all integers.Besides that, it also including couple dozens other audit fields which i only care about a few.

Things I have tried that doesn't work:

Google/StackOverFlow Search and tried different approach.

1st
add the following generator(I believe this one is default):

<generator class="assigned" />

so the hbm composit-id is like following:

<composite-id class="CollabPoApprovalKey" name="key">
    <key-property name="Id" column="ID" type="long" />
    <key-property name="suId" column="SU_ID" type="integer" />
    <key-property name="po" column="PO" type="integer" />
    <key-property name="line" column="LINE" type="short" />
    <generator class="assigned" />
</composite-id>

2nd

Tried use this method save(String entityName, Object object) by

this.collabPoApprovalGateway.save("CollabPoApproval",CollabPoApproval)

don't work

3rd

Trid use this method saveOrUpdate(Object object)

still don't work.

Upvotes: 4

Views: 1461

Answers (1)

Prerak Tiwari
Prerak Tiwari

Reputation: 3466

If you want to insert the new record then create new object of type CollabPoApproval and copy the values from the selected object instead of modifying it. Hibernate looks into the reference of the object, in this case the reference is not changing that why it is firing update statement instead of insert.

CollabPoApproval collabPoApproval  = this.collabPoApprovalGateway.findById(key);
CollabPoApproval collabPoApprovalNew = new CollabPoApproval ();
//copy collabPoApproval values to collabPoApprovalNew 
//do other modification
this.collabPoApprovalGateway.save(collabPoApprovalNew );

Upvotes: 2

Related Questions