简体   繁体   English

JPA/Hibernate 乐观锁按版本插入场景

[英]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 .如果由于系统的遗留特性而不能使用乐观锁,您仍然可以使用带有 JPA 的悲观锁 - 实际使用取决于您的实现 Alternatively you can lock the rows you want to update with a NATIVE QUERY - for example in Oracle you can use SELECT ... FOR UPDATE :或者,您可以使用NATIVE QUERY锁定要更新的行 - 例如在 Oracle 中,您可以使用SELECT ... FOR UPDATE

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

You can manage the optimistic lock, using @Version .您可以使用@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有关 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).请注意,如果您的表充满数据并且无法删除并再次创建它,您必须将版本列添加到您的表中(通过本机查询)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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