扫码一下
查看教程更方便
MapStruct 可以无缝地将数字转换为所需格式的字符串。 我们可以在 @Mapping
注解期间将所需的格式作为 numberFormat 传递。 例如,考虑以数字形式存储的金额以货币格式显示的情况
打开映射隐式类型转换章节中更新的项目映射。
使用以下代码创建 CarEntity.java
CarEntity.java
package com.jiyik.entity; public class CarEntity { private int id; private double price; 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; } }
使用以下代码创建 Car.java
Car.java
package com.jiyik.model; public class Car { private int id; private String price; 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; } }
使用以下代码创建 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") Car getModelFromEntity(CarEntity carEntity); }
使用以下代码创建 CarMapperTest.java
CarMapperTest.java
import com.jiyik.entity.CarEntity; import com.jiyik.mapper.CarMapper; import com.jiyik.model.Car; import org.junit.Test; import org.mapstruct.factory.Mappers; import static org.junit.Assert.assertEquals; public class CarMapperTest { private CarMapper carMapper = Mappers.getMapper(CarMapper.class); @Test public void testEntityToModel() { CarEntity entity = new CarEntity(); entity.setPrice(345000); entity.setId(1); Car model = carMapper.getModelFromEntity(entity); assertEquals(model.getPrice(), "$345000.00"); assertEquals(entity.getId(), model.getId()); } }
运行以下命令来测试映射。
$ mvn clean test
执行结果如下