Hibernate: Duplicate entry for key error troubleshooting

background:

Company business needs:

1. Merge two users, including asset account information.
2. The user's points account has ID number (idNum) and real name (realName) information, and it is a joint unique index.
3. For the convenience of description, suppose there are two users A and B, and the account information of user B needs to be merged into the account of user A. And user B's account idNum and realName fields are not empty (realName: Zhang San, idNum: 123), user A's account idNum and realName are empty.

field User A User B
actual name null Zhang San
identification number null 123

question:

When merging:
1. Open the transaction;
2. First fill in the idNum and realName information of user B into the account of user A;
3. Then update the idNum and realName of user B to "Zhang San-1" and "123-1 ”;
4. Update B user account;
5. Update A user account;
6. Submit the transaction ( error!!! )

reason:

The error is reported as two pieces of data violate the unique index rule. That is to say, the idNum of the two data is consistent with the realName data, both are "Zhang San" + "123"!
I update the data of account B first before updating account A. The normal understanding is that the realName and idNum of account A are "Zhang San" + "123" at this time, and the data of B has been modified to other data. There should be only one data as In the case of "Zhang San" + "123", why is "Duplicate entry" reported?

Speculation:

Since I didn't study the hibernate source code, I dare not jump to conclusions. Since the transaction is opened, all updated data is still in the cache and not written to the database. At this point, the data status should be as follows:
insert image description here
when the transaction is committed, the data is verified. It is found that the unique index value of the A user account in the cache is the same as that of the B user account in the database, and then an exception is thrown.

Solution:

Before setting the idNum and realName of the user account A, save the idNum and realName of the B account, then update the B account idNum=123-1, realName=Zhang San-1, and then update the B account, call the flush() method to flush the cached data After flashing into the database, the data of "Zhang San" + "123" does not exist in the database at this time. Finally, there is no problem in submitting the transaction.

Summarize:

This speculation is not necessarily correct, you need to check the official documentation of hibernate to confirm it! You also need to understand the three states of hibernate beans: transient (transient state), persistent (persistent state) and detached (free state)!

Guess you like

Origin blog.csdn.net/ls0111/article/details/90025358