使用Mapstruct进行实体转换,在自动生成的class中不是我想要的结果
1.目前有两个实体,一个User,一个UserInfo,其中User对象有一个属性,UserId,UserId是另一个实体,现在需要将UserInfo中的userId,映射到User实体的UserId的id上
public class UserId {
private final String id;
public UserId(String id) {
if (StringUtils.isEmpty(id)) {
throw new IllegalArgumentException("用户id不能为空");
}
this.id = id;
}
public String getId() {
return id;
}
}
@Getter
@AllArgsConstructor
public class User {
private UserId userId;
}
@Data
public class UserInfo {
private String userId;
}
Mapper
@Mapper
public interface UserAssembler {
UserAssembler INSTANCE = Mappers.getMapper(UserAssembler.class);
@Mapping(source = "userId", target = "userId.id")
User userInfoToUser(UserInfo userInfo);
}
public class UserAssemblerImpl implements UserAssembler {
@Override
public User userInfoToUser(UserInfo userInfo) {
if ( userInfo== null ) {
return null;
}
UserId userId = null;
userId = userInfoToUserId( userInfo);
User user = new User(userId);
return user;
}
protected UserId userInfoToUserId(UserInfo userInfo) {
if ( userInfo== null ) {
return null;
}
String id = null;
id = userInfo.getUserId();
UserId userId = new UserId( id );
return userId;
}
}
我希望生成后的结果是,在通过userInfo.getUserId()得到id后,对id进行判空,如果id是空的,直接return null,因为在UserId的构造函数中,会对入参进行判断,所以当id是null的时候,就不能去new UserId出来,这应该如何去实现?
业务层去判断逻辑,你不要在实体类对象中去判断啊。
方法中throw没用,对应的方法上需要throws抛出异常类型。
public UserId(String id) throws IllegalArgumentException {
if (StringUtils.isEmpty(id)) {
throw new IllegalArgumentException("用户id不能为空");
}
this.id = id;
}
调用这个方法的地方,需要处理这个异常。try catch捕获。