Reputation: 1
When I try to store the same entity using the spring JpaRepository multiple times in parallel I get a Duplicate entry for key PRIMARY
. The TestEntity consists of two values, which change frequently, and the TestEntityId stays the same. The idea is to update the TestEntity based on the EmbeddedId using the save method, because I am not sure if the TestEntity already exist in Database.
If this happens frequently for the same EmbeddedId I get the Duplicate entry error pretty fast. I can also reproduce the behavior in a unit test.
When I run the test I get the exception: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '1-2-prov' for key 'PRIMARY'
@Entity
public class TestEntity {
@EmbeddedId
private TestEntityId testEntityId;
@Column
private String value1;
@Column
private String value2;
...
}
@Embeddable
public class TestEntityId implements Serializable {
private double lat;
private double lng;
private String prov;
...
}
@Repository
public interface TestEntityRepository extends JpaRepository<TestEntity, TestEntityId> {
// Empty
}
Testcase
@Test
public void testStoreSameEntryMultipleTimes() {
LongStream.range(1L, 100L).boxed().parallel()
.map((i) -> new TestEntityId(1.0, 2.0, "prov"))
.map((te) -> new TestEntity(te , "value1", "value2"))
.forEach((e) -> testEntityRepository.save(e));
...
}
I already tried to add transactions or different locks on the table as well as other way to declare the composed primary key.
It would be great if you have any idea on how to solve this issue.
Upvotes: 0
Views: 1513
Reputation: 5095
The problem is you're creating 100 entities with the same primary key, instead of using the i
to increment them.
Upvotes: 1