1

I have a Spring REST exported URL where I want to do UPSERT operation. If the row exists it will UPDATE , else it will INSERT. I have earlier been doing POST for CREATE, PATCH for UPDATE and DELETE for Delete.

Is there any way I can have UPSERT operation supported for a URL , using a PUT or so ?

fortm
  • 4,066
  • 5
  • 49
  • 79
  • In REST, PUT is used for updating the existing resource and POST for creation. There is no upsert specified in REST "conventions". Can you explain your use case, what do you need it for? – Rafal G. Jan 18 '15 at 18:46
  • R4J, I wanted to give an API where if resource is not existing it falls backs to INSERT else does an UPDATE. This would normally need 2 Calls from client , 1 to GET and another to POST/PUT. So it is a convenience API that I am trying to expose. I was thinking if Handlers could be used like BeforeSave , BeforeUpdate ? – fortm Jan 19 '15 at 06:27
  • 1
    And what is your "PK"? Is this a business/natural ID of some sort or do you have your own, auto generated one? If the latter, then there is going to be a problem with duplicated records. – Rafal G. Jan 19 '15 at 07:18
  • PK is auto generated ones from MySQL , id column as datatype Long – fortm Jan 19 '15 at 08:24
  • so basically table is missing unique constraints, table has columns id, user_id and lang_id , now there should be a unique constraint on user_id and lang_id. Since I don't have bandwidth to add this constraints, can only handle in API. and for that I needed a check here to not insert yet another same combination of user_id + lang_id if exists – fortm Jan 19 '15 at 08:29
  • How is the upsert supposed to work if the id is auto-generated? – a better oliver Jan 19 '15 at 15:31
  • I agree my use case is less of UPSERT and more of conditonal INSERT that when not found then insert. I think I can use HandleSave for that. Given Entity is Identifiable, I suppose the SDR could also leverage on that and use getId() to get auto generated PK – fortm Jan 20 '15 at 05:54
  • @RafalG. I'm not 100% sure of REST conventions, but the HTTP [`PUT`](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6) method is defined to support upserts: "If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, [...] the origin server can create the resource with that URI." – M. Justin Jan 13 '21 at 18:37

1 Answers1

3

PUT method invokes resource creation operation if a resource you are updating does not exists as evident from this code snippet on PUT method.

Stackee007
  • 3,196
  • 1
  • 26
  • 39
  • 1
    I tried this and it inserted new record when no row was found by {id} and the new row that is generated has new id as created by sequence. If {id } is business/natural ID I understand it would have solved duplicate record issue. – fortm Jan 20 '15 at 17:56