【发布时间】:2010-11-10 15:21:45
【问题描述】:
考虑 postgres 数据库中的以下模式。
CREATE TABLE employee
(
id_employee serial NOT NULL PrimarKey,
tx_email_address text NOT NULL Unique,
tx_passwd character varying(256)
)
我有一个 java 类,它执行以下操作
conn.setAutoComit(false);
ResultSet rs = stmt.("select * from employee where tx_email_address = 'test1'");
if (!rs.next()) {
Insert Into employee Values ('test1', 'test1');
}
ResultSet rs = stmt.("select * from employee where tx_email_address = 'test2'");
if (!rs.next()) {
Insert Into employee Values ('test2', 'test2');
}
ResultSet rs = stmt.("select * from employee where tx_email_address = 'test3'");
if (!rs.next()) {
Insert Into employee Values ('test3', 'test3');
}
ResultSet rs = stmt.("select * from employee where tx_email_address = 'test4'");
if (!rs.next()) {
Insert Into employee Values ('test4', 'test4');
}
conn.commit();
conn.setAutoComit(true);
这里的问题是如果有两个或多个上述事务的并发实例试图写入数据。只有一个事务最终会成功,其余事务会抛出 SQLException“唯一键约束违规”。我们如何解决这个问题。
PS:我只选择了一张表和简单的插入查询来演示这个问题。我的应用程序是基于 java 的应用程序,其唯一目的是将数据写入目标数据库。并且可能有并发进程这样做,并且某些进程可能会尝试写入相同的数据的可能性很高(如上例所示)。
【问题讨论】:
-
为什么会出现这样的问题?如果您将应用程序设计为多个线程/进程可以插入相同的数据,那么您希望其他事务失败。
标签: java postgresql jdbc transactions