Home > Software engineering >  During the update it increments a new data Springboot java
During the update it increments a new data Springboot java

Time:04-09

I'm training with springboot,h2 hibernate, tried to do a full crud. Everything works except that when I modify a data, it modifies the selected data but it adds one more to my list. Who can tell me what is wrong with my code? thanks in advance.

controller:

@PutMapping("/updateMovie/{id}")
    public ResponseEntity updateMovie(@PathVariable Long id, @RequestBody Movie movie){
        
        return ResponseEntity.ok(movieService.updateMovie(id, movie));
    }

Service

public Movie updateMovie(@PathVariable Long id, @RequestBody Movie movie){

        Movie currentMovie = movieRepository.findById(id).orElseThrow(RuntimeException::new);
        currentMovie.setTitle(movie.getTitle());
        currentMovie.setDescription(movie.getDescription());
        currentMovie.setDuration(movie.getDuration());
       
        return movieRepository.save(movie);
    }

Model

public class Movie {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private Long id;

    @Column(name= "title")
    private String title;

    @NonNull
    @Column(name= "duration")
    private Integer duration;

    @Column(name= "description")
    private String description;
}

CodePudding user response:

You have a bug in your code. Instead of updating the existing record, you just save the inputed movie object, which will result in creating a new row in the db.

Should be return movieRepository.save(currentMovie);

  • Related