如何解决Java ModelMapper:将DTO映射到EmbeddedId实体类
我想知道是否可以将DTO映射到带有复合pk的实体类。我一直在阅读有关PropertyMap的ModelMapper文档,但无法使其正常工作。
代码如下:
PlanDTO :
public class PlanDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String formula;
private String frequency;
private String pricingtable;
// getters and setters omitted
PlanId :
@Embeddable
public class PlanId implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
public BillingPlanId() { }
public PlanId(Long id,String name) {
this.id = id;
this.name = name;
}
// getters and setters omitted
}
计划:
@Entity
@Table(name = "plan")
public class Plan implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
private PlanId id;
@Column(name = "formula")
private String formula;
@Column(name = "frequency")
private String frequency;
@Column(name = "pricingtable")
private String pricingTable;
public Plan() { }
//setters and getters omitted
}
这是ModelMapper配置。
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setAmbiguityIgnored(true);
PropertyMap<PlanDTO,Plan> itemMap1 = new PropertyMap<PlanDTO,Plan>() {
protected void configure() {
map().setFormula(source.getFormula());
map().setFrequency(source.getFrequency());
map().setId(new Plan(source.getId(),source.getName()));
map().setPricingTable(source.getPricingtable());
}
};
modelMapper.addMappings(itemMap1);
}
但这会在运行时debug image
发生配置是否有问题?我想念什么吗?
解决方法
我不太确定您的问题是什么,但仅使用一个属性映射即可进行映射:
modelMapper.addMappings(new PropertyMap<PlanDTO,Plan>() {
@Override
protected void configure() {
map().getId().setName(source.getName());
}
});
所有其他字段均应按其名称隐式映射。甚至是PlanId.id
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。