我有两种类型的数据,我要地图:
SignUpUserDto:
public class SignUpUserDto {
private String firstName;
private String lastName;
private String username;
private String email;
private String password;
private String title;
}
SignUpUser:
@Entity
public class SignUpUser {
private Long id;
private String firstName;
private String lastName;
private String username;
private String email;
private String password;
private Title title;
}
标题:
public enum Title {
JUNIOR("junior"),
MIDDLE("middle"),
SENIOR("senior"),
MANAGER("manager");
private final String title;
Title(final String title) {
this.title = title;
}
public String toString() {
return this.title;
}
}
对于DTO冠军成员是一个字符串。
对于实体标题构件为标题。
映射器看起来应该怎么样?
我应该通过转换已经在标题服务?
@Mapper(componentModel = "spring")
public interface SignUpUserMapper {
SignUpUserMapper INSTANCE = Mappers.getMapper(SignUpUserMapper.class);
@Mapping(target = "title", expression = "title")
public SignUpUserDto signUpUserToSignUpUserDto(SignUpUser signUpUser, String title);
@Mapping(target = "title", source = "title")
public SignUpUser signUpUserDtoToSignUpUser(SignUpUserDto signUpUserDto, Title title);
}
或者我应该做的转换映射?
@Mapper(componentModel = "spring", imports = Title.class)
public interface SignUpUserMapper {
SignUpUserMapper INSTANCE = Mappers.getMapper(SignUpUserMapper.class);
@Mapping(target = "title", expression = "java(signUpUser.getTitle().toString())")
public SignUpUserDto signUpUserToSignUpUserDto(SignUpUser signUpUser);
@Mapping(target = "title", source = "java(new Title(signUpUserDto.getTitle()))")
public SignUpUser signUpUserDtoToSignUpUser(SignUpUserDto signUpUserDto);
}
我应该通过转换已经在服务的标题?
你肯定建议立即进行删除不能这样做。这是转换器的工作,而不是服务的
请尝试以下方法:
1)添加转换方法枚举类
enum Title {
...
public static Title fromString(String title) {
if (title != null) {
for (Title t : Title.values()) {
if (t.toString().equals(title)) {
return t;
}
}
}
return null;
}
}
2)加入2层转换的方法来映射接口(仅适用于Java的8+)
@Mapper(componentModel = "spring")
public interface SignUpUserMapper {
SignUpUserDto signUpUserToSignUpUserDto(SignUpUser signUpUser);
SignUpUser signUpUserDtoToSignUpUser(SignUpUserDto signUpUserDto);
default String fromEnum(Title title) {
return title == null ? null : title.toString();
}
default Title toEnum(String title) {
return title == null ? null : Title.fromString(title);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句