Feature Req: Support a default value in enum mappings

1,199 views
Skip to first unread message

Yogesh Bhootada

unread,
Jan 8, 2015, 3:31:57 PM1/8/15
to mapstru...@googlegroups.com
I have a scenario where I am mapping an Enum (lets call is as FooEnum - FOO, BAR, FOOBAR) in DTO to another Enum (lets call it BarEnum - FOO, BAR) in my business entity, FOO being the default value I want for this enum.

here is what I have in my mapper:

@Mappings({
   
@Mapping(source = "FOO", target = "FOO"),
    @Mapping(source = "BAR", target = "BAR"),
})
FooEnum mapEnum(BarEnum enum);


@Mappings({
   
@Mapping(source = "FOO", target = "FOO"),
    @Mapping(source = "BAR", target = "BAR"),
    @Mapping(source = "FOOBAR", target = "FOO"),
})
BarEnum mapEnum(FooEnum enum);

If there is some way where I can specify that any unknown values from source enum (FOOBAR in my FooEnum above) should match to a default enum value in my target Enum (FOO in BarEnum), that would make things a lot simpler. Anytime I add a new value in my FooEnum, I have to come and change this mapper as well to put the missing mapping.

Gunnar Morling

unread,
Jan 8, 2015, 4:56:54 PM1/8/15
to Yogesh Bhootada, mapstru...@googlegroups.com
Hi,

no, it is not possible atm., but it's an interesting proposal.

I believe it generally should be a conscious decision how a given source enum value should be mapped. So I kind of like the fact that the generator raises an error in case a new source enum member is added which is not mapped and thus forces you to think about the mapping.

But I can see that a default mapping might make sense in certain cases (e.g. if there is some sort of "UNKNOWN" member in the target enum). So I wouldn't object to add support for this, provided the user has to "opt in" to enable such default mapping, keeping today's behavior the default.

The first approach coming to mind would be a special value for the source() attribute representing "any" source enum member. It would have to be a value which is no legal Java enum member name. WDYT e.g. about this:

    @Mapping(source = "BAR", target = "BAR"),
    @Mapping(source = "#ANY", target = "FOO"),
    BarEnum mapEnum(FooEnum enum);

Thinking about it, we'd likely need two reserved values, "#ANY" for mapping any source member not explicitly configured and something like  "#ANY_UNMAPPED" for mapping those source members which are not configured explicitly nor have a corresponding target member of the same name.

Could you open an issue in our tracker (https://github.com/mapstruct/mapstruct/issues) for this?

Thanks,

--Gunnar


--
You received this message because you are subscribed to the Google Groups "mapstruct-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mapstruct-use...@googlegroups.com.
To post to this group, send email to mapstru...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages