简体   繁体   中英

Dozer Mapper is not mapping directly

I have a SourceClass with following parameters as:

class SourceClass{
   public Integer a;
   public Integer b;
}

And a DestinationClass as:

class DestinationClass {
   public Integer a;
   public Integer b;
}

And here is my test code:

public static void main(String[] args) {
    Mapper mapper = new DozerBeanMapper();

    SourceClass src= new SourceClass();
    src.a= 1;
    src.b= 2;

    DestinationClass dest = mapper.map(src, DestinationClass.class);

    System.out.println(dest.a  + "  " + dest.b);
}

The last line of the code is showing as null null , now I have tried by giving the getter/setter as well but didn't worked, I finally got the output by specifying @Mapping annotation giving the name of the variable to map like @Mappinf("a"), but as you see my variable names are same, can't dozermapper do it by itself?Because here it is written that it maps the same named variables automatically.

Ok so first of all either change SourceClass variables to Strings or change src.a and src.b values to be Integers.

Secondly you need to have getters and setters in both SourceClass and DestinationClass because dozer relies on them regardless if the variables are public or private.

The following solution works:

public class SourceClass{
private Integer a;
private Integer b;

public Integer getA(){
    return a;
}

public void setA(Integer a){
    this.a = a;
}

public Integer getB()
{
    return b;
}

public void setB(Integer b){
    this.b = b;
}
}

public class DestClass{
    private Integer a;
    private Integer b;

    public Integer getA(){
        return a;
    }

    public void setA(Integer a){
        this.a = a;
    }

    public Integer getB(){
        return b;
    }

    public void setB(Integer b){
        this.b = b;
    }
}

public static void main(String[] args)
    {
        Mapper mapper = new DozerBeanMapper();

        SourceClass src = new SourceClass();
        src.setA(1);
        src.setB(2);

        DestClass dest = mapper.map(src, DestClass.class);

        System.out.println(dest.getA() + "  " + dest.getB());
    }

I hope this helps.

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