简体   繁体   中英

Java ModelMapper: map DTO to EmbeddedId entity class

I want to know if it's possible to map a DTO to an entity class with a composite pk. I've been reading ModelMapper documentation about PropertyMap but I can't make it work.

Here is the code:

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
}

Plan :

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

Here is the ModelMapper configuration.

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

But this happens at runtime debug image

Is there something wrong with the configuration? Do I miss something?

I am not quite sure what is your problem but mapping should be quite easy with a just one property mapping:

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

All the other fields should be implicitly mapped by their name. Even the PlanId.id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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