gpt4 book ai didi

java - 如何针对不同的数据类型使用MapStruct?

转载 作者:行者123 更新时间:2023-12-02 09:19:45 26 4
gpt4 key购买 nike

我想要映射两种类型的数据:

注册用户Dto:

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,标题成员是一个字符串

  • 对于实体标题成员来说,是一个标题

映射器应该是什么样子?

我应该传递已在服务中转换的标题吗?

@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);
}

最佳答案

Should I pass title already converted in Service?

你绝对不应该这样做。这是转换器的工作,而不是服务的工作

尝试以下方法:

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)在Mapper接口(interface)中添加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);
}
}

关于java - 如何针对不同的数据类型使用MapStruct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57305532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com