MapStruct - 使用 numberFormat


MapStruct 无缝处理数字到所需格式的字符串的转换。我们可以在 @Mapping 注解期间将所需的格式作为 numberFormat 传递。例如,考虑以数字存储的金额以货币格式显示的情况。

  • 来源- 实体的价格为 350。

  • 目标- 模型显示价格为 350.00 美元。

  • numberFormat - 使用格式 $#.00

例子

打开项目映射,如Eclipse 中的“映射隐式类型转换”一章中更新的那样。

使用以下代码创建 CarEntity.java -

CarEntity.java

package com.tutorialspoint.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 -

汽车.java

package com.tutorialspoint.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.tutorialspoint.mapper;

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

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

使用以下代码创建 CarMapperTest.java -

CarMapperTest.java

package com.tutorialspoint.mapping;

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;

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

输出

一旦命令成功。验证输出。

mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...