//源对象
@Data
public class EntityJ implements Serializable{
private Date valJ;
}
//目标对象
@Data
public class EntityK implements Serializable{
private String valK;
}
//Date转String的特殊处理
@Mapper
public class DateMapper {
public String asString(Date date) {
return date != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH)
.format(date) : null;
}
public Date asDate(String date) {
try {
return date != null ? new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH)
.parse(date) : null;
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
//转换方法
@Mapper(uses = DateMapper.class)
public interface SpecConvertMapper {
SpecConvertMapper INSTANCE = Mappers.getMapper(SpecConvertMapper.class);
@Mappings({
@Mapping(target = "valK", source = "valJ"),
})
EntityK entityJtoK(EntityJ entityJ);
}
//调用方法
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws ParseException {
EntityJ entityJ= new EntityJ();
EntityK entityK= new EntityK();
entityJ.setValJ(new Date());
entityK = SpecConvertMapper.INSTANCE.entityJtoK(entityJ);
System.out.println(entityK.toString());
SpringApplication.run(DemoApplication.class, args);
}
//结果
使用场景
目标对象需要对源对象的字段的转型做特殊处理,如所有的日期格式,数字金额格式调整