繁体   English   中英

Java ModelMapper:将 DTO 映射到 EmbeddedId 实体类

[英]Java ModelMapper: map DTO to EmbeddedId entity class

我想知道是否可以将 DTO 映射到具有复合 pk 的实体类。 我一直在阅读关于 PropertyMap 的 ModelMapper 文档,但我无法让它工作。

这是代码:

计划DTO

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

计划编号

@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);
}

但这发生在运行时调试图像

配置有问题吗? 我错过了什么吗?

我不太确定您的问题是什么,但映射应该很容易,只需一个属性映射:

modelMapper.addMappings(new PropertyMap<PlanDTO, Plan>() {
    @Override
    protected void configure() {
        map().getId().setName(source.getName());
    }            
});

所有其他字段都应按其名称隐式映射。 甚至PlanId.id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM