I'm having following issue with duplicated inserts in case of concurrent requests.
I have two tables:
create table tbl (
val varchar2(1000)
);
create table tbl2 (
val varchar2(1000)
);
I need to insert some value in table tbl2
only in case if table tbl
is empty. So, in my Java code I do in transaction with isolation level = READ COMMITED:
//start transaction
int result = jdbcTemplate.queryForInt("select count(*) from tbl");
if (result == 0) {
int update = jdbcTemplate.update("insert into tbl2(val) values(?)", "di" + UUID.randomUUID().toString());
}
//end transaction
The problem here is: Somebody could actually insert data between if (result == 0)
and my update statement. So I'll have duplicate entries.
My example is oversimplified, but my real case is much more complicated, but the basic idea is the same: I need to make several selects from within of Javacode before inserting.
So, how is it possible to avoid such kind of situation(I'm interested in db side solution and in java side solution)?
P.S. Database is Oracle.