简体   繁体   中英

Dozer Deep Mapping with Annotations

Unable to map deep mapping from Source class to Target class SourceEmployee.Address.houseName to TargetEmployee.houseName

Source object class

public class SourceEmployee 
{   
    private String empName;
    private Address addr;


    enter code here

    @Mapping("empName")
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }   
    public Address getAddr() {
        return addr;
    }

    public void setAddr(Address addr) {
        this.addr = addr;
    }   
}

Address class

public class Address 
{
    private String houseName;
    public String getHouseName() {
        return houseName;
    }
    public void setHouseName(String houseName) {
        this.houseName = houseName;
    }
}

target object

public class TargetEmployee 
{

    private String empName;
    private String houseName;

    public String getHouseName() {
        return houseName;
    }
    public void setHouseName(String houseName) {
        this.houseName = houseName;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
}

Main class copying from source to destination

public class CopyAttributes 
{

    public static void main(String args[])
    {
        SourceEmployee sourceEmp = new SourceEmployee();
        sourceEmp.setEmpName("Rafi");

        Address adr = new Address();        
        adr.setHouseName("Aashiyana");
        sourceEmp.setAddr(adr);

        Mapper mapper = new DozerBeanMapper();
        TargetEmployee destObject = mapper.map(sourceEmp, TargetEmployee.class);

        System.out.println(destObject.getEmpName());
        System.out.println(destObject.getHouseName());

    }
}

In case someone else run into the same problem, I manage to correct that case by doing this :

public class TargetEmployee 
{

    private String empName;
    private String houseName;

    @Mapping("addr.houseName")
    public String getHouseName() {
        return houseName;
    }
    public void setHouseName(String houseName) {
        this.houseName = houseName;
    }
    public String getEmpName() {
        return empName;
    }
    public void setEmpName(String empName) {
        this.empName = empName;
    }
}

The

@Mapping("empName")

set in SourceEmployee Isn't necessary

it's enough to add this annotation in the source class (SourceEmployee):

@Mapping("this")
private Address addr;

In fact, "this" means "remain on the same node"; after that, houseName will match between Address and TargetEmployee.

;)

Alex

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