携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第三十天,点击查看活动详情
当使用mapstruct进行数据转换时,如果参数格式不匹配,如Test1中格式为Date,Test2中的格式为String类型,则需要将参数转换一下格式。
@Data
public class Test1{
private String name;
private String age;
private Date date;
}
@Data
public class Test2{
private String name;
private String age;
private String date;
}
对象转换映射器的写法应该为
@Mapper(componentModel = "testMapper")
public interface TestMapper {
InvoiceDataMapper INSTANCE = Mappers.getMapper(TestMapper.class);
@Mappings({
@Mapping(target = "date", source = "date", dateFormat = "yyyyMMddHHmmss")
})
Test2 test1toTest2(Test1 test1);
}
如果需要在转换前做下其他判断,如不为空,格式判断等,可以再写一个Mapper文件,作为数据转换文件,在映射器方法中使用这个转换文件。
public class DateMapper {
//将字符串类型的时间戳转换为LocalDateTime格式的时间,如果转换失败或者时间戳为空则返回null
public LocalDateTime asDate(String timestamp) {
try {
if (StringUtils.isEmpty(timestamp)) {
return null;
}
LocalDateTime time = LocalDateTime.ofEpochSecond(Long.valueOf(timestamp.length() > 10 ?
timestamp.substring(0, 10) : timestamp), 0, ZoneOffset.ofHours(8));
return time;
} catch (Exception e) {
return null;
}
}
//将String类型数据转换为BigDecimal类型,如果转换失败则返回null
public BigDecimal asBigDecimal(String num) {
try {
return new BigDecimal(num);
} catch (Exception e) {
return null;
}
}
}
在使用的时候,映射器需要指向该转换文件
//使用use来指定数据转换的方法,当数据有相同的类型转换会自动调用该方法
@Mapper(componentModel = "testMapper",uses = DateMapper.class)
public interface TestMapper {
InvoiceDataMapper INSTANCE = Mappers.getMapper(TestMapper.class);
Test2 test1toTest2(Test1 test1);
}
或者需要两个list数据相互转换,这时候就可以先进行对象直接的数据转换,再定义一个list数据相互转换的映射器,该方法会自动指定为对象转换后的数据组装为list数据返回 使用的映射器示例为
@Mapper(componentModel = "testMapper",uses = DateMapper.class)
public interface TestMapper {
InvoiceDataMapper INSTANCE = Mappers.getMapper(TestMapper.class);
Test2 test1toTest2(Test1 test1);
//此时 test1stoTest2s 的实现为循环调用 test1toTest2 并继承了 test1toTest2 的属性映射
List<Test2> test1stoTest2s(List<Test1> test1);
}