I have the next entities:
@Entity
@Data
@EqualsAndHashCode(callSuper = true)
public class Student extends BaseEntity {
private String identifier;
@NotNull
@Embedded
private UserInformation userInformation;
@Embeddable
@ToString
public class UserInformation {
@NotNull
@Size(min = 1, max = 40)
private String firstName;
@NotNull
@Size(min = 1, max = 40)
private String lastName;
@NotNull
private LocalDate dateOfBirth;
@OneToOne
private Address address;
@Enumerated(EnumType.STRING)
private Gender gender;
}
And I create a DTO for the Student class:
@Data
@ToString
public class CreateStudentDTO {
@NotNull
private UserInformationDTO userInformation;
}
@Data
@ToString
public class UserInformationDTO {
@NotNull
@Size(min = 1, max = 40)
private String firstName;
@NotNull
@Size(min = 1, max = 40)
private String lastName;
}
But because UserInformationDTO and UserInformation I did not find a solution to map them. This is what I tried in the Controller:
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private ModelMapper modelMapper;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CreateStudentDTO createStudent(@RequestBody CreateStudentDTO studentDTO) {
System.out.println("dto: " + studentDTO);
TypeMap<CreateStudentDTO, Student> propertyMapper = modelMapper
.createTypeMap(CreateStudentDTO.class, Student.class);
propertyMapper.addMapping(CreateStudentDTO::getUserInformation, Student::setUserInformation);
Student student = modelMapper.map(studentDTO, Student.class);
System.out.println(student);
return null;
}
}
But the field in Student after mapping will be: userInformation=UserInformation(firstName=null, lastName=null, dateOfBirth=null, address=null, gender=null)
I want to map only the firstName and lastName for first, then I can map others if this works.