Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

During the update it increments a new data Springboot java

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading