【发布时间】:2020-02-27 05:41:42
【问题描述】:
在我的 dto 类中:
private String password;
在我的模型类中:
private byte[] password;
我想使用 mapStruct 将 String 转换为 byte[]。有人可以帮忙吗
提前致谢。
【问题讨论】:
标签: spring-boot mapping mapstruct
在我的 dto 类中:
private String password;
在我的模型类中:
private byte[] password;
我想使用 mapStruct 将 String 转换为 byte[]。有人可以帮忙吗
提前致谢。
【问题讨论】:
标签: spring-boot mapping mapstruct
最好为String 和byte[] 之间的映射提供默认方法。
例如:
@Mapper
public MyMapper {
Model fromDto(Dto dto);
default byte[] toBytes(String string) {
return string != null ? string.getBytes() : null;
}
}
这样,您将让 MapStruct 自动为您在 Dto 和 Model 之间的所有其他字段执行操作,并将 String 和 byte[] 之间的映射留给 toBytes 方法。
【讨论】:
假设你有这个类。
public class Source {
private String password;
//getters and setters
}
public class Destination {
private byte[] password;
//getters and setters
}
您可以创建自定义映射器。
@Mapper
public abstract class MyMapper {
public Destination sourceToDest(Source source) {
Destination dest = new Destination();
dest.setPassword(source.getPassword().getBytes());
return dest;
}
}
然后
MyMapperImpl mapper = new MyMapperImpl();
Destination dest = mapper.sourceToDest(source);
【讨论】: