简体   繁体   English

如何从 Java 锁定数据库记录?

[英]How do I lock database records from Java?

I'm developing a database program in Java with dbf.我正在用 dbf 用 Ja​​va 开发一个数据库程序。 I need to know how to lock the database records from the Java side.我需要知道如何从 Java 端锁定数据库记录。

Example: we have a database table cheques with 5 records in the table ( record 1 through 5 ).示例:我们有一个数据库表cheques表中的 5 条记录( record 15 )。 There are 2 users, user-1 and user-2 .有 2 个用户, user-1user-2 user-1 accesses record 1 and user-2 tries to access record 1 at the same time. user-1访问record 1user-2尝试访问record 1 I want to lock record 1 to prevent access to that record by user-2 while user-1 is accessing it.我想锁定record 1以防止user-2user-1访问它时访问该记录。 How do I do this in Java?我如何在 Java 中做到这一点?

In case of MySQL, you can use, SELECT FOR UPDATE statement for locking the records.在 MySQL 的情况下,您可以使用SELECT FOR UPDATE语句来锁定记录。 Lock will not be released until the transaction completes or rolls back.在事务完成或回滚之前不会释放锁。 More on the same here .更多关于相同的here

It depends on the environment you are working on.这取决于您工作的环境。 for a container managed transaction your container manages the transactions for you and all you have to do is to set the Lockmode to lockmode.write.对于容器管理的事务,您的容器会为您管理事务,您所要做的就是将 Lockmode 设置为 lockmode.write。 What this does is that it blocks all write access to the class methods while userA is accessing record 1. On the other hand for a stand alone application you can just add Synchronization key word to your method to control concurrent access.它的作用是在用户 A 访问记录 1 时阻止对类方法的所有写访问。另一方面,对于独立应用程序,您只需将 Synchronization 关键字添加到您的方法中即可控制并发访问。 I hope this helps.我希望这有帮助。

Not every database supports per-record locking.并非每个数据库都支持按记录锁定。

Generally, if you are in EE environment, you can use JPA EntityManager#find() method to lock certain record.一般在EE环境下,可以使用JPA EntityManager#find()方法来锁定某条记录。

Full usage will be like that完全使用将是这样

// EntityManager em;
YourClass obj = em.find(YourClass.class, primaryKey, LockModeType.WRITE);
// do something
em.merge(obj);

After transaction commit the record(s) will be released.事务提交后,记录将被释放。

In non-EE environment, as Darshan Mehta said, connection.createStatement().execute("SELECT * FROM table FOR UPDATE") will be the solution.在非 EE 环境中,正如 Darshan Mehta 所说, connection.createStatement().execute("SELECT * FROM table FOR UPDATE")将是解决方案。

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

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