MapStruct如何String转Date

翻阅官方文档https://mapstruct.org/documentation/stable/reference/html/#datatype-conversions

发现官方有个例子,关于自定义转换器规则的例子

When generating code for the implementation of the carToCarDto() method, MapStruct will look for a method which maps a Date object into a String, find it on the DateMapper class and generate an invocation of asString() for mapping the manufacturingDate attribute.

在为实现的carToCarDto()方法生成代码时,MapStruct将查找一个将日期对象映射到字符串中的方法,在DateMapper类中找到它,并生成一个asString()调用来映射manufacturingDate属性。(以上为原文翻译,依次类推,在需要String转date的mapper上调用改转换器,则会自动调用asDate()方法) 

所以只需要在要转换的mapper上加上 uses=DateMapper.class ,并新建DateMapper.class,添加自定义的String转Date方法即可。下面是例子:

public class DateMapper {

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

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

通过调用自定义转换器实现String到Date的转化,通过如下方法进行调用

@Mapper(uses=DateMapper.class)
public class CarMapper {

    CarDto carToCarDto(Car car);
}
原创文章 96 获赞 201 访问量 67万+

猜你喜欢

转载自blog.csdn.net/sinat_29774479/article/details/102745582