Hibernate first obtains an object data, modifies the data, and adds the new data to the database. What do you need to pay attention?

Source: Internet
Author: User

1. What I am doing a simple save operation today is to locate me for an hour. In this nonsense, I get data from the database through the interface,CodeAs follows:

// Obtain the current process data
Taskrundata taskrundataoriginal = This. taskrundataservice. Get (New Long (runtaskid ));

Then modify some field values for taskrundataoriginal and set the primary key to null, so that a new piece of data is added. Think of a few seconds, and then call save happily,

However, an exception occurred while saving. The primary key cannot be set to null. OK, I created a new taskrundata object and rebuilt the data in taskrundataoriginal, so I guess it's OK. The result is OK. A new piece of data is added, but an SQL statement is added, that is, update is executed to update the data obtained at the beginning, that is, two identical data records appear in the database (but the primary keys are different ).

I am depressed. I quickly got to Google, but I didn't find anything. Later I thought it was a start.The old object is obtained in the session, so this object has already been synchronized with the database, or is associated with it, so the modification will also be committed in the Spring transaction. OK, I wrote a clone method for the taskrundata JavaBean. I first cloned one and then modified the cloned data. After testing, I finally got OK. Alas. Lessons learned

Summary: From gethibernatetemplate (). get (this. persisttype, ID); In the get data, do not directly modify its value, so that when the Spring transaction is committed, the initial data will be updated.

If you want to modify, modify the cloned data.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.