简体   繁体   中英

JPA/Hibernate optimistic lock by version in insert scenario

I have a table which holds a balance of customers' balances.

| Customer_Id | Request_Id | Blance | Request_Date |

Each request that is received to the application, I select the last request and read its balance and do some process and finally insert a new record in the table with a new balance (Old Balance - Request Amount). My challenge is when two requests from one customer received to my application and concurrency occurred at this scenario and finally insert a record with the wrong balance. I know optimistic locking helps in update scenarios ideally, but our system is a legacy application, and I can't change the behavior of the system.

If you cannot use optimistic lock is not an option due to the legacy nature of your system you can still use pesimistic locking with JPA - The actual used depends on your implementation . Alternatively you can lock the rows you want to update with a NATIVE QUERY - for example in Oracle you can use SELECT ... FOR UPDATE :

SELECT ... FROM ... WHERE Customer_Id = ... FOR UPDATE

You can manage the optimistic lock, using @Version .

Example : Active optimistic lock management for Test table.

@Entity
@Table(name = "TEST")
public class TestEntity {

    private Long id;
    private String name;

    @Version
    private Long version;

   //getter and setters
}

More information about Optimistic-lock in JPA

By using this annotation, optimistic-lock will be managed automatically by the system and you don't need to do anything.

Notice that , If your table is full of data and it's not possible to drop and create it again, you must add version column to your table(by a native query).

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