Spring Boot – Write UPDATE Methods

In this chapter, we are going to write the Update Methods (PUT) to update records.

So this follows from the same procedure as with the POST methods.

 

  1. Write the updateLocation Methods
  2. Write the updateUser Methods
  3. Write the updatePost Methods
  4. Test the Application

 

1. Write the updateLocation Methods

Open the LocationController file and write the updateLocation method as shown below

@RequestMapping(value = "/locations/{id}", method = RequestMethod.PUT)
public void updateLocation(@RequestBody Location location, @PathVariable String id) {

     locationService.updateLocation(id, location);

}

Listing 1.0:updateLocation for the LocaitonController

 

After you write this code, you will have an error. So you need to add the updateLocation method in the LocationService file as shown below

public void updateLocation(String id, Location location) {

   for(int i = 0; i < locations.size(); i++) {

	Location l = locations.get(i);

	if (l.getId().equals(id)) {
	    locations.set(i, location);
	}
   }		
}

Listing 1.1: updateLocation for the LocationService class

 

In the code above, we simply loop through the collection to find a matching id. Then we replace location at that position with the passed in Location.

 

 

2. Write the updateUser Methods

Open the UserController file and write the updateUser method as shown below

@RequestMapping(value="/users/{id}", method = RequestMethod.PUT)
public void getUser(@PathVariable String id, @RequestBody User user) {

    userService.updateUser(id, user);

}

Listing 1.2: updateUser for the UserController class

 

Similarly, add the updateUser method in the UserService file as shown below

public void updateUser(String id, User user) {

    for(int i = 0; i < users.size(); i++) {

	User u = users.get(i);

	if(u.getId().equals(id)) {

	     users.set(i, user);

	     return;
	}
    }
}

Listing 1.3:updateUser for the UserService class

 

 

3. Write the updatePost Methods

Open the PostController file and write the updatedPost method as shown below.

@RequestMapping(value="/posts/{id}", method = RequestMethod.PUT)
public void updatePost(@PathVariable String id, @RequestBody Post post) {

      postService.updatePost(id, post);

}

Listing 1.4: updatePost for the PostController class

 

Similarly, add the updatePost method in the LocationService file as shown below

public void updatePost(String id, Post post) {

    for(int i = 0; i < posts.size(); i++) {

	Post p = posts.get(i);

	if(p.equals(post)) {

	     posts.set(i, post);
	}
    }
}

Listing 1.5:updatePost for the postService class

 

 

4. Test the Application

Now, you can use Advanced REST Client to test the update methods.

You do it almost the same way as the POST methods. But this time you need to specify the id in the url as well.

I recommend you watch the video.

Next, we would write the DELETE methods.