我有一个用户 ID 类,它只包含一个字符串。 我的 API 将其公开为字符串,因此我想使用 MapStruct 来“解开”该值。
示例:
record UserId(String id) {}
@Mapper
public abstract class UserMapper {
@Mapping(target = ".", source="userId.id")
protected abstract String toApi(UserId userId);
}
我希望这能起作用,甚至向 MapStruct 指出哪个成员用于目标值。映射器应该简单地传递
UserId
中包含的字符串并将其作为输出传递。但 MapStruct 创建一个新的空字符串并返回它,而不与源成员交互(除了空检查之外):
(生成的代码)
@Override
protected String toApi(UserId id) {
if ( id == null ) {
return null;
}
String string = new String();
return string;
}
这显然是错误的,我不想要一个新的空字符串,我想要UserId中包含的字符串。我无法找出正确的注释来使其发挥作用。有什么想法吗?
下面列出的我的解决方法是编写一个自定义映射方法来执行此操作,但似乎很奇怪,没有办法让 MapStruct 为我生成此代码。
@Mapper
public abstract class UserMapper {
// ... other mapping methods ...
protected String toApi(Userid userId) {
return userId.id();
}
}
据我所知,这是不可能的。 MapStruct 映射对象之间的字段,并且
String
没有可映射的可访问字段。
我知道的唯一解决方案是手动编写实现。
default String toApi(UserId userId) {
return userId.id();
}
如果有可能用单个方法实现接口
String id()
,映射器可以变得更加灵活:
interface Identifiable {
String id();
}
record UserId(String id) implements Identifiable {}
record UserId2(String id) implements Identifiable {}
default String toApi(Identifiable identifiable) {
return identifiable.id();
}