Search code examples
springspring-boothibernatejpadto

How can I update Entity data from DTO using java spring boot?


Currently I am working on a webserver-project where I have this entity:

@Entity
public class Person {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "person_gen")
    @GenericGenerator(name = "person_gen", strategy = "native")
    private Integer id;


    @Past
    @DateTimeFormat(pattern = "dd.MM.yyyy")
    @Column(name = "date_of_birth", columnDefinition = ColumnDefinition.DATE)
    private LocalDate dateOfBirth;
}

For the HTML-form I wanted to have the localdate as a string, so I wrote a DTO and a Converter, that can convert Person to PersonDTO and the other way round.

My Problem:

(1) A user creates a GET request and receives a website with all person data (packed in a DTO), which he may edit. (2) The data will be sent back to the server using POST. (3) The server receives a DTO and converts it back to a Person.

As soon as I call save on the according service/repository, I get a duplicate entry. Instead of that, I want to UPDATE all fields that were edited. I even tryed to write a custom method like this:

@Query("UPDATE Person p SET ... WHERE p.id = :id")
void updateAllFields(@Param(value = "id") Integer id,...);

But also this approach did not work. How can I update? Is there an annotation missing or something?


Solution

  • Found it out!

    My problem was, that I had many fields declared as

    @ManyToMany
    

    With a join table in between those entities. This was the problem, because then an update or delete is quite difficult. Instead, I now modeled them according to this example with JoinColumns:

    https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany

    and it works really nice!