How to update object fields from another object using Modelmapper

时间:2018-03-07 13:26:13

标签: java object copy deep-copy modelmapper

I am planning to write a method which use to update a MyObject object with not null fields of another MyObject object.

private void updateMyObject(MyObject sourceObject, MyObject destinationObject) {
    ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
    mapper.map(sourceObject, destinationObject);
}

public class MyObject {
    long id;

    long durationInMilliSecounds;

    //...getters and setters 
}

In here destinationObject is not getting updated. Can anybody suggest the issue of this code.

2 个答案:

答案 0 :(得分:0)

你似乎错过了一些代码。也许错误在于该代码。我猜你的模型没有getMap和setter,这是ModelMapper所必需的。

以下代码按预期工作:

public class modelMapperTest {
    public static void main(String[] args) {
    ModelMapper mapper = new ModelMapper();
    mapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());

    MyModel sor = new MyModel(null, 5);
    MyModel des = new MyModel("yyy", 0);        

    System.out.println(des);
    mapper.map(sor, des);
    System.out.println(des);
}

public class MyModel {
    private String s;
    private int i;

public String getS() {
    return s;
}

public void setS(String s) {
    this.s = s;
}

public int getI() {
    return i;
}

public void setI(int i) {
    this.i = i;
}

public MyModel(String s, int i) {
    super();
    this.s = s;
    this.i = i;
}

@Override
public String toString() {
    return "MyModel [s=" + s + ", i=" + i + "]";
}

}

打印:

MyModel [s = yyy,i = 0]

MyModel [s = yyy,i = 5]

答案 1 :(得分:0)

我之前使用的是ModelMapper版本0.6.5,并将其升级到1.1.0问题已修复