I have created simple CRUD api using Spring Data JPA in my Spring boot application.My Post method in the controller looks like below:-
@RequestMapping(value = "/article", method = RequestMethod.POST, produces = "application/json")
public Article createArticle(@RequestBody Article article) {
return service.createArticle(article);
}
Service Method is as follows:-
@Override
public Article createArticle(Article articleModel) {
return repository.save(articleModel);
}
My JsonPayload looks like below:
{
"article_nm":"A1",
"article_identifier":"unique identifier"
}
Now I want to make my POST request as Idempotent so that even if i got the json payload with the same article_identifier
again It would not create a record in DB.
I can't do any scheme/constraint change in database and article_identifier
field is also not primary key in table.
I understand that first I can check in database and return the saved record in response if it already exists but here if multiple request (original and duplicate request) comes at same time, both will check in database and would not find any record with that identifier and will create 2 record (one for each). Also as it's a distributed application how can i maintain the consistency across multiple database transactions.
How can I use some locking mechanism so that there would not be 2 records with same article_identifier
ever. Can somebody please suggest some refers how to implement it in Spring boot ?
article_identifier
the primary key in the database?GET
,PUT
andDELETE
are meant to be idempotent. Doing so withPOST
might confuse API consumer.