Mapstruc自定义转换器

日期转换器

定义日期Mapper

public class DateMapper {
    public String toString(Date date) {
        return date != null ? new SimpleDateFormat("yyyy-MM-dd").format(date) : null;
    }

    public Date toDate(String date) {
        try {
            return date != null ? new SimpleDateFormat("yyyy-MM-dd").parse(date) : null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

定义对象转换Mapper

/**
 * 自定义日期格式转换映射器
 * uses = DateMapper.class
 */
@Mapper(uses = DateMapper.class,componentModel="spring")
public interface User5Mapper extends BaseMapper<UserDTO, UserVO1> {
    
}

对象中的 Date 字段转换成不同格式的时间文本,比如转换成 yyyy-MM-dd 和 yyyy/MM/dd 两种格式

@Named("dateMapper1")
public class DateMapper1 {
    public String toString(Date date) {
        return date != null ? new SimpleDateFormat("yyyy-MM-dd").format(date) : null;
    }

    public Date toDate(String date) {
        try {
            return date != null ? new SimpleDateFormat("yyyy-MM-dd").parse(date) : null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
@Named("dateMapper2")
public class DateMapper2 {
    public String toString(Date date) {
        return date != null ? new SimpleDateFormat("yyyy/MM/dd").format(date) : null;
    }

    public Date toDate(String date) {
        try {
            return date != null ? new SimpleDateFormat("yyyy/MM/dd").parse(date) : null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

@Mapper(uses = {
        DateMapper1.class,
        DateMapper2.class
},componentModel="spring")
public interface User6Mapper extends BaseMapper<UserDTO, UserVO1> {
   

    @Mappings({
            @Mapping(source = "createTime", target = "createTime", qualifiedByName = {"dateMapper1"}),
            @Mapping(source = "updateTime", target = "updateTime", qualifiedByName = {"dateMapper2"})
    })
    @Override
    UserVO1 to(UserDTO var1);
}

数值转换器

private Double wallet;
private String wallet;

 @Mapping(source = "wallet", target = "wallet", numberFormat = "$#.00")

BigDecimal转换

private BigDecimal deposit;
private String deposit;
@Mapping(source = "deposit", target = "deposit", numberFormat = "#.##E0")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值