Member-only story
Spring, Why Did You Terminate My Transaction?
Starting with Uniqueness
After writing code for over ten years, I have seen many methods of handling uniqueness constraints implemented in code rather than in the database.
To this day, I am still puzzled as to why these people do not use the unique index of the database. But I do not want to know the answer.
Their approach is very simple. If they need to ensure that a name is unique, they first execute a query statement with Java code:
select * from example where name = ?
Then, based on the return value, if it is null, it means that this name does not exist, and then they can execute the insert statement:
insert into example(name) values(?)
If it is not null, it means that this name already exists, and they return a message indicating that the name already exists.
If the system has low concurrency or it is not tested intentionally, this method works fine.
However, in reality, occasional issues arise, resulting in duplicate name records.
A similar situation occurs with the lottery issue, which is determining whether there are any prizes left.