MapStruct 使用 dateFormat

MapStruct 可以无缝地将日期转换为所需格式的字符串。 我们可以在 @Mapping 注释期间将所需的格式作为 dateFormat 传递。 例如,考虑以数字形式存储的日期以特定格式显示的情况。

  • Source - 实体的日期为 GregorianCalendar(2015, 3, 5)。
  • Target - 将日期显示为 05.04.2015 的模型。
  • dateFormat - 使用格式 dd.MM.yyyy

示例

打开 numberFormat 映射章节中更新的项目映射。

使用以下代码更新 CarEntity.java

CarEntity.java

package com.jiyik.entity;

import java.util.GregorianCalendar;

public class CarEntity {
    private int id;
    private double price;
    private GregorianCalendar manufacturingDate;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public GregorianCalendar getManufacturingDate() {
        return manufacturingDate;
    }
    public void setManufacturingDate(GregorianCalendar manufacturingDate) {
        this.manufacturingDate = manufacturingDate;
    }
}

使用以下代码更新 Car.java

Car.java

package com.jiyik.model;

public class Car {
    private int id;
    private String price;
    private String manufacturingDate;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getPrice() {
        return price;
    }
    public void setPrice(String price) {
        this.price = price;
    }
    public String getManufacturingDate() {
        return manufacturingDate;
    }
    public void setManufacturingDate(String manufacturingDate) {
        this.manufacturingDate = manufacturingDate;
    }
}

使用以下代码更新 CarMapper.java

CarMapper.java

package com.jiyik.mapper;

import com.jiyik.entity.CarEntity;
import com.jiyik.model.Car;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper
public interface CarMapper {
    @Mapping(source = "price", target = "price", numberFormat = "$#.00")
    @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
    Car getModelFromEntity(CarEntity carEntity);
}

使用以下代码更新 CarMapperTest.java

CarMapperTest.java

package com.jiyik.mapper;

import com.jiyik.entity.CarEntity;
import com.jiyik.model.Car;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

@Mapper
public interface CarMapper {
    @Mapping(source = "price", target = "price", numberFormat = "$#.00")
    @Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
    Car getModelFromEntity(CarEntity carEntity);
}

运行以下命令来测试映射。

$ mvn clean test

执行结果如下

MapStruct 使用 dateFormat

查看笔记

扫码一下
查看教程更方便