Mapstruct 简明教程
MapStruct - Mapping Map
使用 Mapstruct,我们可以使用 @MapMapping 注释创建映射对象映射。其他映射规则与我们迄今为止看到的一样。
Syntax
@Mapper
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}
以下示例演示了相同内容。
Example
在Eclipse中打开在 Mapping List 章节中更新的项目映射。
使用以下代码创建 UtilityMapper.java −
UtilityMapper.java
package com.tutorialspoint.mapper;
import java.util.GregorianCalendar;
import java.util.Map;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
@Mapper
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}
使用以下代码创建 UtilityMapperTest.java −
UtilityMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.mapper.UtilityMapper;
public class UtilityMapperTest {
private UtilityMapper utilityMapper = Mappers.getMapper(UtilityMapper.class);
@Test
public void testMapMapping() {
Map<Long, GregorianCalendar> source = new HashMap<>();
source.put(1L, new GregorianCalendar(2015, 3, 5));
Map<String, String> target = utilityMapper.getMap(source);
assertEquals("05.04.2015", target.get("1"));
}
}
运行以下命令以测试映射。
mvn clean test
Output
命令成功后。验证输出。
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.327 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
...