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

时间:2020-10-14 16:10:42

标签: java modelmapper

我想知道是否可以将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

发生

配置是否有问题?我想念什么吗?

1 个答案:

答案 0 :(得分:0)

我不太确定您的问题是什么,但仅使用一个属性映射即可进行映射:

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

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

相关问题