【发布时间】:2019-11-26 18:00:42
【问题描述】:
我有两种类型的数据要映射:
SignUpUserDto:
public class SignUpUserDto {
private String firstName;
private String lastName;
private String username;
private String email;
private String password;
private String title;
}
注册用户:
@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,标题成员是 String。
对于entity,title 成员是一个Title。
映射器应该是什么样子的?
我应该通过 Service 中已转换的标题吗?
@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 中进行转换吗?
@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);
}
【问题讨论】:
-
你不能这样做
new Title(...)因为 Title 是 Enum 类
标签: java spring-boot mapstruct