So here, we have a Enitity class - Contact
public class Contact {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name",nullable = false)
private String name;
@Column(name = "email",nullable = false,unique = true)
private String email;
@Column(name = "phone",nullable = false)
private String phone;
}
A DTO class - ContactDto
public class ContactDto {
private Long id;
private String fname;
private String lname;
private String email;
private String phone;
}
I want to map the fname and lname with the name attribute in the contact and vice versa. How to achieve this solution?
I tried using MapStruct library. I am getting confused how to implement this logic. So kindly help me either with MapStruct or ModelMapper.
@Mapper
public interface ContactMapper {
ContactMapper INSTANCE = Mappers.getMapper(ContactMapper.class);
ContactDto mapToContactDto(Contact contact);
Contact mapToContact(ContactDto contactDto);
}
This is what i tried doing using Mapstruct.
I recommend to read this question. how-to-convert-entity-to-dto-and-vice-versa
If you want to continue using MapStruct here is good explanation. Baeldung - mapstruct
Usually it is better to write your own mapper, becuase you have full controll what is happening and have less headache if some tests stop working in future.
Personally I would do like this: Of Method in Mapper