Java 从多个会话中与数据库进行安全通信

Java safe communication with database from multiple sessions

我必须在 Java 为我的公司开发一个小型应用程序,它应该显示数据库中的数据。显示的数据应该可以在 gui 中编辑,并使用保存按钮将编辑后的数据写入数据库。 我现在的问题是如何处理数据库通信,因为多个用户将同时使用该应用程序?我认为如果 A 人在看数据而 B 人进行更改,就会出现问题。如果现在人 A 保存了他的更改,则人 B 的数据将丢失。

我在互联网上找不到任何东西,因为我不知道必须使用哪个关键字进行搜索。我只能找到一个叫做 dao 模式的东西,但我不认为那是我要找的东西。

希望你能帮助我。

您的问题称为数据库锁定;

Locking is perhaps the most ignored persistence consideration. Most applications tend to ignore thinking about concurrency issues during development, and then smush in a locking mechanism before going into production. Considering the large percentage of software projects that fail or are canceled, or never achieve a large user base, perhaps this is logical. However, locking and concurrency is a critical or at least a very important issue for most applications, so probably should be something considered earlier in the development cycle.

If the application will have concurrent writers to the same objects, then a locking strategy is critical so that data corruption can be prevented. There are two strategies for preventing concurrent modification of the same object/row; optimistic and pessimistic locking. Technically there is a third strategy, ostrich locking, or no locking, which means put your head in the sand and ignore the issue.

Optimistic Locking

Optimistic locking assumes that the data will not be modified between when you read the data until you write the data. This is the most common style of locking used and recommended in today's persistence solutions. The strategy involves checking that one or more values from the original object read, are still the same when updating it. This verifies that the object has not changed by another user in between the read and the write.

Pessimistic Locking

Pessimistic locking means acquiring a lock on the object before you begin to edit the object, to ensure that no other users are editing the object. Pessimistic locking is typically implemented through using database row locks, such as through the SELECT ... FOR UPDATE SQL syntax. The data is read and locked, the changes are made and the transaction is committed, releasing the locks.

有关更多信息以及如何在 Java 和 JPA 中实施它,请阅读 Java Persistence Locking