简体   繁体   中英

Why do not I get the id when mapping from DTO to entity with mapstruct?

I have an API with spring boot and I use mapstruct and I just want to update the Person entity. For this, having PersonDto update Person.

What I have so far: Mapper:

@Mapper
public interface PersonMapper {
   PersonDto toPersonDto(Person person);
   Person toPerson(PersonDto personDto);

   Person updatePersonFromDto(PersonDto persoonDto, @MappingTarget 
      Person document);
}
  1. In service layer: Find Person:

     public PersonDto updatePerson(Long personId) { PersonDto personDto = personService.findById(personId) .orElseThrow(() -> new PersonNotFoundException(id)); personDto.set(...) //set others properties Person person = personMapper.toPerson(personDto); person = personMapper.updatePersonFromDto(personDto, person); personRepository.save(person); return personMapper.toPersonDto(person); }` 

My question, is there a strategy or a better way of update an entity from a DTO?

Edit: I was able to solve a part, now I do not lose the id, but I still create a new object instead of updating it. The id is in AbstractPersistableEntity.

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Person extends AbstractPersistableEntity<ID> implements Serializable {
  @Column
  private String name;
  @Column
  private String lastName;
  @Column
  private Integer age;
}

public class PersonDto {
   @JsonProperty(access = JsonProperty.Access.READ_ONLY)
   private Long id;
   private String name;
   private String lastName;
   private Integer age;
}

Maybe it is not the most optimal or correct solution but it works. I made the following modifications to the mapper:

 @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
Person updatePersonFromDto(PersonDto persoonDto, @MappingTarget 
  Person document);

 @ObjectFactory
 default Person updatePerson(PersonDto personDto, Person person){
    if (personDto != null){
        Long id = person.getId();
        Person resultPerson = updatePersonFromDto(personDto, person);
        resultPerson.setId(id);
        return resultPerson;
    }
    return null;
}

Then from the service just call:

person = personMapper.updatePerson(personDto, person);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM