Spring Boot | 🙋♂️ PUT/PATCH REST APIs - All you need to know with Example | JavaTechie
ฝัง
- เผยแพร่เมื่อ 8 ธ.ค. 2022
- This tutorial will guide you practical understanding about PUT & PATCH HTTP Method with Live example .
#JavaTechie #Patch
Spring boot microservice Live course Just started (Recordings available)
Hurry-up & Register today itself!
COURSE LINK : javatechie5246.ongraphy.com/
PROMO CODE : Java40
GitHub:
github.com/Java-Techie-jt/pat...
Blogs:
/ javatechie
Facebook:
/ javatechie
guys if you like this video please do subscribe now and press the bell icon to not miss any update from Java Techie
Disclaimer/Policy:
--------------------------------
Note : All uploaded content in this channel is mine and its not copied from any community ,
you are free to use source code from above mentioned GitHub account - วิทยาศาสตร์และเทคโนโลยี
Contents are really easy to understand. Thank you for sharing this.
Wow .. I was literally searching for this patch rest api , and here it is .. thank you so much for creating the amazing content as always
Thank you for sharing your knowledge and above all for having the subtitles activated, people like me who do not speak English it is vital for me that the subtitles are activated to be able to understand your explanations.
This is a great video, mate!!! Well done and thanks :)
Faced this question just a few days back. You are reading minds.
Amazing, exactly what i was looking for!
Thank you for this class. I learned a lot. And Thank you for sharing your knowledge with us.
Great video, even we can use beanwrapper object from spring framework to update the values it internally uses reflection
Thank you so much Sir for this new http method 😊😊
Thanks bro. Very Helpful
very well explained 💯🔥
nice explained!! thanks
you are a life saver ❤️
Thanks cleared 🙏
Thank you for this helpful video sir
Got it, Good explanation
awesome!
Thank you sir 😊
Thank you so much atlast my error got solved
many thanks
Useful videos
helped thanks, like )
your explanation very nice
The only thing that I missed was the validation of the properties entered from the user. In this way we set them directly without validating them. And that's a bit tricky to do using Map as an Object instead of a custom DtoRequest class containing only the fields we need to change, OR the full Entity Class with NotNull being the field we only need to update (because imagine if we have entity with 150 fields for example). It would be great if somebody shows the full PATCH method including validation.
I believe Validation will work because if you observe we are converting value to object using reflection so that time all your validation will be considered but not sure need to check
@@Javatechie Maybe you could show the video, or at least source code in github where we can validate fields in Map fields?
Because no one can avoid human mistakes(
I already share the source code link in the video description please check once
I am not able to update Date by using patch mapping can you help me..
You have awesome teaching skills bro. Learn a lot from you. Can you create tutorial on how to create soap to rest for existing projects . Thanks you
Okay sure i will give a try
Bro ur videos are too good no doubt.
But request you to make videos where you teach how to understand the code written by someone else ( may be in java framework or some other language framework) and situation when there are less people to give KT
This is typical situation in service based companies. Would appreciate a similar video with tips to tackle such situation
It depends on the java and spring boot framework version
Please do one video on RestvAPI for Post,GET,Delete,PUT,Patch..its very helpful us
The quality of the video will be very good
Thanks for the vídeo, very helfull.
Just to contribute, maybe the 'id' field should not be allowed as part of payload or should be checked against the path param in order to avoid object update sabotages. []'s
Correct we should add validation to not pass I'd
👍👍
What should I do if I want to make one field null?
i am not able to update date by using patch mapping
Recently I used this method, what about when you have a oneToMany relationship and you have a list from other relational entity? If the other table doesn’t have a record you have to implement extra logic to make a post method otherwise use reflection for patch?
i have the same question
But we can use @putmapping and pass single field for update so why we need two methods
Hi Basant, If we see the sql statement that is generated in both PUT and PATCH, in both the case it is first fetching the record and then updating all the fields (irrespective that we passed one or two values in PATCH),
For that you need to use @SqlUpdate annotations
Sir,
In PUT Mappping as per your code. If we want to update name and price only, and if we send only name and price in body using Postman, then in business logic, if I only set Name and set Price, then PUT Mapping will also work like PATCH Mappping.
So my question is, While using PUT mapping, why we need to "set" those values that we do not want to update?
For example:
In the below code, if I only set Name and Price.
public Product updateProduct(int id, Product productRequest) {
// get the product from DB by id
// update with new value getting from request
Product existingProduct = repository.findById(id).get(); // DB
existingProduct.setName(productRequest.getName());
existingProduct.setPrice(productRequest.getPrice());
return repository.save(existingProduct);
}
but we dont know which fields will be coming from postman...so we put all fields open to be updated
Nice video, but how to do without reflection? I'm building with GraalVM and Micronaut (compile time compilation).
HI, Thank You for your example, but I have problem when trying to set Double value
ReflectionUtils.setField(field, document, value);// Can not set java.lang.Long field Document.documentSize to java.lang.String] with root cause
It's expected long but somehow you are giving string please check that
Hello. This is a great approach, but one question comes to mind, how do we then validate some of the data being passed?
Not getting you could you please elaborate little bit
Thank you very much for this video. I have a question: How can I make it so that it is not allowed to load empty or blank fields from PATCH?
You need add field level Validation
Can we use Optional class to handle null pointer exceptions?
Yes that's recommended
This seems to work only if the value is a string or integer. But if I have a Date or another object (say Address in Person) this approach fails as it tries to directly set the field without converting to the right object first. Or am I missing something? Could you show in another video how to deal with these use cases?
It should work with any data type. Are you getting any error
Best part 12:41 Why this guy is crying..🤣🤣🤣🤣😆
Really appreciate your efforts buddy
If we keep Map fields instead of RequestBody in this PUT API ... Then, it will do a partial update... Right
No that's not the case here i have used a map to pass some specific field for an update as a request
@thanooj yes it will still work as business logic (service layer) is written by us, so we can change the logic. But we have to follow certain rules to differentiate the things that's the only reason that we have various http methods. I mean we can also use Get method and write the business logic to create object there is harm
The same code i tried with putmapping also, it works same. Then why do i need to use patch here … anu particular reasons ??
Even the same code you can do in the post why do we need to use put then
We can update single field using put mapping why we need two methods
In patch mapping you are receiving values in Map but in real scenario you will send the object bcos you need to have validate annotations over DTO. How will you iterate Fields when it's not map and it's an actual product dto in patch mapping?
map key values are converted into Field object which will have all the validation associated with that field.I think we can validate with that
@hiren Modi Generally we do 3 ways validation one is from Request object (DTO) , other validations will be added in entity level and then business validations will be handled in validators class. If DTO validation is bypassed we entity will take care of field level validations on top of validators class for the respective entity will look for business validations. Hope you got the answer
isnt reflection slow and we should avoid it?
Any reason please why you are expecting it will be slow. Could you please add some more insights
one line code you made to 10 lines without explaining what is the advantages? what will happen if it saves entire object.
It seem you didn’t go through the videos
What is the difference between @PatchMapping and @DynamicUpdate?
Both context are different buddy please watch Both the video you will understand
Hi
Can you please tell me that how to make an request param as optional in repository at run time.
Please consider the situation,
UPDATE REQUEST FROM FRONTEND
FrontEnd -> {id, name, present} - they need to change the present status(Here user can change anything, they can change name alone or they can change both name and present )
Backend -> In my backend , i have it as below in repo layer
@Modifying
@Query("Update set id = ?1, name = ?2, present =?3")
Integer updateStudent(Integer id, Stirng name, String present);
Scenario:
here present status will be always changed whenever the user send request, But user send request to change NAME sometimes (Not all times)
In such case , user pay load will be like below
{
"id":1
"name" : " " (Empty string or NULL - user don't want to change name)
"present": "yes"
}
Existing data in repo for student id 1 is
id =1, name = "someName", present = "No"
Now based on above mentioned query table is updated and resultant as below
id =1, name = null, present = "Yes"
This is the ISSUE, since i mentioned the name on set parameter it updated as it.
CAN YOU PLEASE TELL ME HOW TO MAKE IT OPTIONAL. Like if name given then it should update or Else It should update the present column only and not the NAME
Thanks
Then go for put not patch and while updating just get the value what user is giving and set it to the existing object and save it . Check my plan update method
@@Javatechie thank you for the reply. let me try 🙂
@@Javatechie can you share link please
Check-out my spring boot crud example
We can update single field using put mapping why we need two methods 😮
Sorry to say but ,whatever logic you have written inside the service class's method which is associated with PATCH method, just write the same logic within the PUT method, then it will also start to perform the same operation. Where is the difference then. This example is showing two types of logic 1) checking the fields and then update, 2) Setting all the request values to the object.It's not the difference between the properties of PUT/PATCH.
Buddy purpose of put and patch i have explained in video. If that is the case then we can start using the put method while persisting records to db as well right? Then why are there 2 different http method post and put
@@Javatechie I have the same question for POST,PUT,PATCH and was looking for a practical difference. Meanwhile learning docker from your docker playlist🙂.
@@SattuSoni no worries i will upload a video about different types of http method by taking idempotent nature .
@@Javatechie Please upload the PUT PATCH POST practical difference example demo
better to use DynamicUpdate on Entity level no need of patch here
😂 Why this guy is crying
good
Field field = ReflectionUtils.findField(XYZ.class, key); on this line I am getting error as "Can not resolve method on object xyz" @Java Techie
Sir,
In PUT Mappping as per your code. If we want to update name and price only, and if we send only name and price in body using Postman, then in business logic, if I only set Name and set Price, then PUT Mapping will also work like PATCH Mappping.
So my question is, While using PUT mapping, why we need to "set" those values that we do not want to update?
For example:
In the below code, if I only set Name and Price.
public Product updateProduct(int id, Product productRequest) {
// get the product from DB by id
// update with new value getting from request
Product existingProduct = repository.findById(id).get(); // DB
existingProduct.setName(productRequest.getName());
existingProduct.setPrice(productRequest.getPrice());
return repository.save(existingProduct);
}
I think irrespective of what method we are using, main logic is in service layer. That's the main thing. Like you said we can also use Get Method and create or update the record in service layer. But we have to follow some standard process to differentiate the things
Sir,
In PUT Mappping as per your code. If we want to update name and price only, and if we send only name and price in body using Postman, then in business logic, if I only set Name and set Price, then PUT Mapping will also work like PATCH Mappping.
So my question is, While using PUT mapping, why we need to "set" those values that we do not want to update?
For example:
In the below code, if I only set Name and Price.
public Product updateProduct(int id, Product productRequest) {
// get the product from DB by id
// update with new value getting from request
Product existingProduct = repository.findById(id).get(); // DB
existingProduct.setName(productRequest.getName());
existingProduct.setPrice(productRequest.getPrice());
return repository.save(existingProduct);
}
Ok but consider this scneario where user may have 50 fields.
In put mapping for user just think the size of json for update.Also the more size of json more time it takes to travel so it will maximize the time taken
Now in patch only fields which are changed can be send.Using it the request body is shorter.Also easier to handle.Also faster.
Sorry for my english but thats advantage