Java 如何使用modelMapper转换嵌套类(非相等类)
我是后端方面的新手,我想在我的项目中使用modelmapper。我知道如何在基本级别上使用modelmapper 以下是我的实体类:Java 如何使用modelMapper转换嵌套类(非相等类),java,spring,modelmapper,Java,Spring,Modelmapper,我是后端方面的新手,我想在我的项目中使用modelmapper。我知道如何在基本级别上使用modelmapper 以下是我的实体类: public class Content { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false, unique = true) private int id; @ManyTo
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 Response {
private String title;
private Double createdDate;
private String userId;
}
那我想要什么?
有一个API的主体:
response: {
"title": "title",
"createdDate": "1616758604",
"userId": "101010"
}
我想将此响应转换为以下内容:
Content: {
"title": "title",
"createdDate": "1616758604",
"User" : {
"userId" : "101010"
"name" : "",
"phoneNumber" : "",
"email" : ""
}
}
注:最后我用JSON格式写了“内容”。但是我需要JAVA语言。如果我正确理解了您的问题,那么您的问题是将用户ID转换为相应的用户并希望使用该库。因此,您可以使用提供的类。我使用了您的示例,添加了getter/setter,并创建了一个ModelMapper实例,该实例将响应转换为内容对象(见下文)
//首先是一些示例数据
用户=新用户();
user.userId=“abc”;
user.name=“name”;
user.email=“mail”;
var响应=新响应();
response.createdDate=112390582。;
response.title=“titel”;
response.userId=“abc”;
//模拟用户数据库
Map users=Map.of(user.userId,user);
//模型映射器
var mapper=newmodelmapper();
setMatchingStrategy(MatchingStrategies.STRICT);
转换器conv=(in)->in.getSource()==null?null:users.get(in.getSource());
createTypeMap(Response.class、Content.class)
.addMappings(mapping->mapping.using(conv.map)(Response::getUserId,Content::setUser));
//映射
Content=mapper.map(响应,Content.class);
Content: {
"title": "title",
"createdDate": "1616758604",
"User" : {
"userId" : "101010"
"name" : "",
"phoneNumber" : "",
"email" : ""
}
}
// 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);