MapStruct 映射枚举 Enum

Mapstruct 自动映射枚举。 具有相同名称的枚举会自动映射。 如果名称不同,我们可以使用 @ValueMapping 注解进行映射。

语法

@Mapper
public interface UtilityMapper {
@ValueMapping(source = "EXTRA", target = "SPECIAL")
PlacedOrderType getEnum(OrderType order);
}

示例

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

使用以下代码创建 OrderType.java

OrderType.java

package com.jiyik.enums;

public enum OrderType {
    EXTRA,
    NORMAL,
    STANDARD
}

使用以下代码创建 PlacedOrderType.java

PlacedOrderType.java

package com.jiyik.enums;

public enum PlacedOrderType {
    SPECIAL,
    NORMAL,
    STANDARD
}

使用以下代码更新 UtilityMapper.java

UtilityMapper.java

package com.jiyik.mapper;

import com.jiyik.enums.OrderType;
import com.jiyik.enums.PlacedOrderType;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;

import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;

@Mapper
public interface UtilityMapper {
    @MapMapping(valueDateFormat = "dd.MM.yyyy")
    Map<String, String> getMap(Map<Long, GregorianCalendar> source);
    Stream<String> getStream(Stream<Integer> source);

    @ValueMapping(source = "EXTRA", target = "SPECIAL")
    PlacedOrderType getEnum(OrderType order);
}

使用以下代码更新 UtilityMapperTest.java

UtilityMapperTest.java

import com.jiyik.enums.OrderType;
import com.jiyik.enums.PlacedOrderType;
import com.jiyik.mapper.UtilityMapper;
import org.junit.Test;
import org.mapstruct.factory.Mappers;

import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

import static org.junit.Assert.assertEquals;

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"));
    }
    @Test
    public void testGetStream() {
        Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
        Stream<String> strings = utilityMapper.getStream(numbers);
        assertEquals(4, strings.count());
    }
    @Test
    public void testGetEnum() {
        PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
        PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
        PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
        assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
        assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
        assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
    }
}

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

$ mvn clean test

执行结果如下

MapStruct 枚举映射

查看笔记

扫码一下
查看教程更方便