mapstruct 1.3 无法将枚举作为第一个方法参数获取

huangapple go评论68阅读模式
英文:

mapstruct 1.3 can not get Enum as first method parameter

问题

以下是您要翻译的内容:

假设您有一个模型类,它只有一个单独的枚举变量。

public class MyModel {
    private MyEnum myEnum;
    // getter and setter
}

您想要一个映射方法,只映射您的那个单独的枚举。

@Mapper(componentModel = "spring")
public interface MyCustomMapper {
    @BeanMapping(ignoreByDefault = true)
    @Mapping(source = "myEnum", target = "myEnum")
    MyModel toMyModel(MyEnum myEnum);
}

但不幸的是,您会得到一个错误:Can't generate mapping method from enum type to non-enum type,这是不正确的,因为它们都是相同的枚举。(@ValueMapping 也不起作用)

显然,这是 MapStruct 的一个问题!

我的解决方案

可能有点傻,但它有效。您需要做的就是添加另一个方法参数(比如一个虚拟的字符串)作为第一个方法参数,然后将您的枚举作为第二个方法参数。您不需要映射虚拟字符串,只需让它存在即可。

@Mapper(componentModel = "spring")
public interface MyCustomMapper {
    @BeanMapping(ignoreByDefault = true)
    @Mapping(source = "myEnum", target = "myEnum")
    MyModel toMyModel(String dummy, MyEnum myEnum);
}

现在,第一个方法参数不是枚举,所以 MapStruct 不会给您带来任何问题。无论如何,如果有更好的解决方案,我会继续寻找。

英文:

say you have a model class which only has a single Enum variable

public class MyModel {

  private MyEnum enum;
  //getter and setter

}

and you want to have a mapper method which only maps that single Enum of yours.

@Mapper(componentModel = "spring")
public interface MyCustomeMapper {

	@BeanMapping(ignoreByDefault = true)
	@Mapping(source = "enum", target = "enum")
	MyModel toMyModel(MyEnum enum);

}

but sadly you get Can't generate mapping method from enum type to non-enum type error which is not right here. because both of them are the same Enum. (and no @valueMapping does not work as well)

clearly it's mapstruct bug!

MY SOLUTION

it might be stupid but it works. all you need to do is to add another method parameter (like a dummy String) as the first method parameter, then your Enum as the second method parameter. you don't need to map your dummy String, just let it be there...

@Mapper(componentModel = "spring")
public interface MyCustomeMapper {

	@BeanMapping(ignoreByDefault = true)
	@Mapping(source = "enum", target = "enum")
	MyModel toMyModel(String dummy, MyEnum enum);

}

now the first method parameter is not an Enum so mapstruct won't make you any problem.
anyway, I'm looking for a better solution if there is anything out there.

答案1

得分: 2

这个错误仅在MapStruct 1.3中存在。从MapStruct 1.4开始,支持将枚举源参数映射到Bean中的属性。

英文:

This error is only present in MapStruct 1.3. Starting from MapStruct 1.4 it is supported to map between an Enum source parameter into a property in a Bean.

huangapple
  • 本文由 发表于 2020年9月23日 06:29:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/64018495.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定