我不知道如何准确地映射它。我需要一个是String,另一个需要是object,所以不幸的是我无法让自己更轻松。
I have a RqgisterRequest class:
public class RegisterRequest {
private String firstName;
private String lastName;
private String email;
private String password;
private Set<String> roles;
这是我的寄存器实例的方法
@PostMapping("/register")
public HttpEntity authenticate(@Valid @RequestBody RegisterRequest registerRequest) {
// create new user account
User user = UserMapper.INSTANCE.registerRequestoUser(registerRequest);
etc..
这里是我的用户DTO
@Data
@NoArgsConstructor
@AllArgsConstructor
public abstract class UserDTO extends BaseDTO {
@JsonProperty("first_name")
private String firstName;
@JsonProperty("last_name")
private String lastName;
@JsonProperty("email")
private String email;
@JsonProperty("password")
private String password;
private Set<Role> roles;
private Set<Appointment> appointments;
(我的用户实体相同)
这是我的UserMapper类:
User registerRequestoUser(RegisterRequest registerRequest);
最后,当我尝试运行该程序时出现错误:错误:(20,11)java:无法将属性“ java.util.Set角色”映射到“ java.util.Set角色”。考虑声明/实现一个映射方法:“ java.util.Set map(java.util.Set value)”。
我应该如何解决这个问题?
由于MapStuct不知道如何将String映射到Role,因此您必须显式定义映射角色。将接口更改为抽象映射器类,然后可以实现到给定属性的特定映射。
@Mappings(value={ @Mapping(source="roles", target="roles", qualifiedByName="customRoleMapper")}
abstract User registerRequestoUser(RegisterRequest registerRequest);
然后实现映射器:
@Named(value = "customRoleMapper")
public List<Role> customRoleMapper(List<String> roles){
//create a new role list where you instantiate a Role from every string and put it into the new list, then return with the new list
}
最简单的方法是提供从String
到Role
的映射方法。
例如
default Role toRole(String role) {
return role != null ? new Role( role ) : null;
}
您可以将其放在映射器或util类中,MapStruct可以将其用于映射。