使用Mapstruct进行对象转换(二)

583 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第二十九天,点击查看活动详情


上一章讲了mapstruct的简单转换,这一章是当一个属性在目标实体中具有不同的名称时参数的转换,或者多个对象与一个对象相互直接的赋值行为。

不同的参数名对象相互赋值,如Test1对象的数据赋值到Test2中

Test1对象为:

@Data
public class Test1{
    private String name;
    private String age;
}

Test2对象为:

@Data
public class Test2{
    private String testName;
    private String testAge;
}

对象转换映射器的写法应该为

@Mapper(componentModel = "testMapper")
public interface TestMapper { 
    InvoiceDataMapper INSTANCE = Mappers.getMapper(TestMapper.class); 
    
    
    @Mappings({
        @Mapping(target = "name", source = "testName")
        @Mapping(target = "age", source = "testAge")
    })
    Test2 test1toTest2(Test1 test1);
}

正式使用时的方法为:

Test2 test2 = TestMapper.INSTANCE.test1toTest2(test1);

如果是两个对象中包含不同的对象名称,如Test1中有个子对象,名称为Person,而Test2中参数在最外层,或者两个对象的参数赋给一个对象的参数中,Test1及PersonExt都有值需要赋给Test2,则对应转换的写法应该为

Test1对象为:

@Data
public class Test1{
    private String name;
    private String age;
    private Person person;
}
@Data
public class Person{
    private String sex;
}
@Data
public class PersonExt{
    private String color;
}

Test2对象为:

@Data
public class Test2{
    private String testName;
    private String testAge;
    private String sex;
    private String color;
}

对象转换映射器的写法应该为

@Mapper(componentModel = "testMapper")
public interface TestMapper {
    InvoiceDataMapper INSTANCE = Mappers.getMapper(TestMapper.class); 
    
    @Mappings({
        @Mapping(target = "name", source = "testName")
        @Mapping(target = "age", source = "testAge")
        @Mapping(target = "test1.person.sex", source = "sex")
        @Mapping(target = "ext.color", source = "color")
    })
    Test2 test1toTest2(Test1 test1,PersonExt ext);
}

如果反过来,Test2中有多个对象,则也是同样的写法,对象名.参数名来指定转换的参数。需要注意的是参数名需要注意大小写,target中使用的应该是参数名而不是方法名,匹配不上会报错。

正式使用时只需要调用Mapper方法即可:

Test2 test2 = TestMapper.INSTANCE.test1toTest2(test1);

mapstruct还有很多操作,比如参数格式转换,对象转换后再进行list转换等。下一章继续写。over