Ravi
Ravi

Reputation: 53

Hibernate: Prevent duplicate rows from being inserted by different threads

I am using hibernate for data persistence with Spring.

Scenario is

Time- 00 Hour:01 Minute:01 Second:100 ms

Time- 00 Hour:01 Minute:01 Second:102 ms

Time- 00 Hour:01 Minute:01 Second:103 ms

Time- 00 Hour:01 Minute:01 Second:104 ms

As both sessions are generating unique identity, hibernate is treating them as separate object and persisting in DB. but this, later on, causes issues in application.

I have unique index too but that includes the Id field also, so DB is also unable to treat them as unique record.

Suggest ways to avoid duplicate insertion.

Upvotes: 0

Views: 279

Answers (2)

LoVas2
LoVas2

Reputation: 1

The easiest solution for me is to add a Multiple-Column Constraint

@Table(name = "Person", uniqueConstraints = @UniqueConstraint(columnNames = {"Name", "LastName"}))

Handle the exception in your code in order to respond to your client.

Upvotes: 0

Sridhar Patnaik
Sridhar Patnaik

Reputation: 1118

If I am understanding this correct, you do not have any uniquely identifiable fields which can tell the backend that incoming record is a duplicate record which is received just few seconds before.

In such case, I am afraid but there may be no direct way to handle this (I may be wrong). There can be indirect ways like

  • Checking audit logs before insertions to check if record with similar data is inserted in last few seconds or minutes.
  • Send a unique code from backend to frontend. frontend has to hit backend using that code. Code gets expired after single use. And check before every insertion if code sent from FE is valid

There can be many such ways and best solution has to be derived based on complexity, performance requirements etc. of your project.

Upvotes: 1

Related Questions