【问题标题】:Java ModelMapper: map DTO to EmbeddedId entity classJava ModelMapper:将 DTO 映射到 EmbeddedId 实体类
【发布时间】:2020-10-14 16:10:42
【问题描述】:

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

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

【问题讨论】:

    标签: java modelmapper


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2021-12-31
      相关资源
      最近更新 更多