I'm struggling with form update. Please consider this example:
// Entity with which I need to perform CRUD operations
public class User {
private String name;
private String email;
private String phone;
private String address;
}
I send to UI is UserDTO:
public class UserDTO {
private String name;
private ContactDataDTO contactDataDTO;
}
public class ContactDataDTO {
private String email;
private String phone;
private String address;
}
My mapper:
@Mapper
public interface UserMapper {
@Mappings({
@Mapping(source="email", target="contactDataDTO.email"),
@Mapping(source="phone", target="contactDataDTO.phone"),
@Mapping(source="address", target="contactDataDTO.address")
})
UserDTO userToUserDTO(User user);
@InheritInverseConfiguration
User updateUserFromUserDTO(UserDTO userDTO, @MappingTarget User user);
}
userToUserDTO() works as expected, but generated userDTOToUser() for me seems wierd:
@Override
public User updateUserFromUserDTO(UserDTO userDTO, User user) {
if ( userDTO == null ) {
return null;
}
String address = userDTOContactDataDTOAddress( userDTO );
if ( address != null ) {
user.setAddress( address );
}
String phone = userDTOContactDataDTOPhone( userDTO );
if ( phone != null ) {
user.setPhone( phone );
}
String email = userDTOContactDataDTOEmail( userDTO );
if ( email != null ) {
user.setEmail( email );
}
user.setName( userDTO.getName() );
return user;
}
Problematic use case:
- Fill in all fields for User.
- Open form again and clear phone field.
- That means to backend I will send smth like this:
userDTO: {
name: 'John Doe';
contactDataDTO: {
email: '[email protected]',
phone: null,
address: 'Home'
}
}
So, user.phone won't be updated, as far as I have null check for it in generated code.
I thought NullValueCheckStrategy is what I need, but there no option which fits me. For now the only option I see - write my own implementation of userDTOToUser() without null checks. Maybe you can advise better solution, cause for me it looks like a problem that can happen in any mapper for a target update from DTO with non-primitive source.
Runnable demo: https://repl.it/@aksankin/SlateblueUnimportantStack
Thanks a lot.
NullValuePropertyMappingStrategy
specifically to control update methods. It seems to me this is not working for nested properties. I need to investigate a bit further. - Sjaak