-2

I am using path variable in url in order to update my object. How can I modify my code for it to work without needing to provide an id in the post body if I already got it in the url?

    public class Person {
        
        private String name;
        private UUID id;
        
        public(UUID id, String name) {
            this.id = id;
            this.name = name;
        }
        ...getters
    } 

Service class

public int updatePerson(UUID id, Person person) {
        String sql = "UPDATE person SET name = ? WHERE id = ?";
        return jdbcTemplate.update(sql, person.getName(), person.getId());
    }

Controller

 @PutMapping("/{id}")
    public int updatePerson(@PathVariable UUID id, @RequestBody Person person) {
        return personService.updatePerson(id, person);
    }
Dave
  • 1
  • 1
  • 9
  • 38

2 Answers2

1

Just change your Service class to use id instead of person.getId():

public int updatePerson(UUID id, Person person) {
    String sql = "UPDATE person SET name = ? WHERE id = ?";
    return jdbcTemplate.update(sql, person.getName(), id);
}
João Dias
  • 16,277
  • 6
  • 33
  • 45
0

If I understand your question, you're looking to use the Person as a payload template for updating an instance of that class.

You can utilise @JsonProperty annotations.

public class Person {
    
    private String name;

    @JsonProperty(access = Access.WRITE_ONLY)
    private UUID id;
    
    public(UUID id, String name) {
        this.id = id;
        this.name = name;
    }
    ...getters
} 
Rstew
  • 585
  • 2
  • 9
  • 21