美文网首页
导入转换方法class

导入转换方法class

作者: 波波维 | 来源:发表于2018-03-14 11:26 被阅读0次
//源对象
@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);
  }

//结果


image.png

使用场景
目标对象需要对源对象的字段的转型做特殊处理,如所有的日期格式,数字金额格式调整

相关文章

网友评论

      本文标题:导入转换方法class

      本文链接:https://www.haomeiwen.com/subject/laxfqftx.html