如何解决如何使用modelMapper转换嵌套类不等价类
我是后端方面的新手,我想在我的项目中使用模型映射器。我知道如何在基本级别使用模型映射器。
有我的实体类:
public class Content {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id",nullable = false,unique = true)
private int id;
@ManyToOne
@JsonIgnore
@JoinColumn(name = "userId",referencedColumnName = "userId",foreignKey = @ForeignKey(name = "fk_content_userId"))
private User user;
@Column(name = "title")
private String title;
@Column(name = "createdDate")
private Double createdDate;
}
public class User {
@Id
@Column(name = "userId",unique = true)
private String userId;
@Column(name = "name")
private String name;
@Column(name = "phoneNumber")
private String phoneNumber;
@Column(name = "email")
private String email;
}
还有我的响应类:
public class Response {
private String title;
private Double createdDate;
private String userId;
}
那我想要什么?
有API的主体:
response: {
"title": "title","createdDate": "1616758604","userId": "101010"
}
我想将此回复转换为以下内容:
Content: {
"title": "title","User" : {
"userId" : "101010"
"name" : "","phoneNumber" : "","email" : ""
}
}
注意:我最后用 JSON 格式写了“内容”。但我需要在 JAVA 中使用它。
解决方法
如果我理解您的问题,您的问题是将 userId 转换为相应的用户并希望使用 ModelMapper 库。因此,您可以使用提供的 converter 类。我使用了您的示例,添加了 getter/setter 并创建了一个 ModelMapper 实例,该实例将 Response 转换为 Content 对象(见下文)。
// First some sample data
User user = new User();
user.userId = "abc";
user.name = "name";
user.email = "mail";
var response = new Response();
response.createdDate = 112390582.;
response.title = "titel";
response.userId = "abc";
// Mock user db
Map<String,User> users = Map.of(user.userId,user);
// The ModelMapper
var mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
Converter<String,User> conv = (in) -> in.getSource() == null ? null : users.get(in.getSource());
mapper.createTypeMap(Response.class,Content.class)
.addMappings(mapping -> mapping.using(conv).map(Response::getUserId,Content::setUser));
// Mapping
Content content = mapper.map(response,Content.class);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。