Amol Kshirsagar
Amol Kshirsagar

Reputation: 253

Race Condition in Postgres SQL using Spring data JpaRepository

I am facing a wierd issue in my implementation where I am persisitng data to a PostgresSQL DB using Spring data JpaRepository

In my Entity class I have the below columns:

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    private int id;
    
    @Column(name = "field1", nullable = false, length = 16)
    private String field1;

    @Column(name = "field2", nullable = false, length = 16)
    private String field2;

    @Column(name = "field3", nullable = false, length = 16)
    private String field3;

I initially avoided declaring the fields above as composite since there were many fields to be dealt with as composite keys. I thought the java code check would do the trick in all scenarios

So basically, I have to maintain the uniqueness of each row based on field1,field2 and field3. That was the basic requirement for which I had checks in my java code that if any entry exists in the DB for the combination of field1,field2 and field3 then I used to throw java exceptions

No two rows can have these values repeating. All was good until the application was tested under some errorneous business scenarios which would never happen in production but got run by mistake

Whats happening now is that if 2 requests are triggered at the exact same instance with the exact same 3 fields above (through a script) then they both enter into the Database since both get the entry check as false

Would declaring all of them as one composite key resolve the situation?

Upvotes: 0

Views: 281

Answers (1)

Cyril G.
Cyril G.

Reputation: 2017

You should define the unique constraint in your database in addition of JPA constraint.

@Entity
@Table(uniqueConstraints={
    @UniqueConstraint(columnNames = {"field1", "field2", "field3"})
}) 
public class MyEntity {
  ...
}

Upvotes: 1

Related Questions