Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Feature] Conditional mapping #2051

Closed
@pherklotz

Description

@pherklotz

Feature proposal

Specify a condition (similar to the expression) for a target. If the condition evaluates to true the mapping will be done. Otherwise nothing happens or the default will be used if specified.

Motivation

Whether a null check nor a presence checker method are sometimes mighty enough to express whether a property should be mapped or not. We use MapStruct to map Protobuf v3 Messages. These can contain oneof fields which can contain only exact one or zero values. If one of the specified values is a primitive datatype like int or long there is no hasXYZ method generated and the default value will be returned from the getter (e.g. zero) this is also the case if another value type is the in the oneof! You have to check the case-Field of the protobuf message to find out which of the oneofs is set. See protobuf documentation about that:

Example

Protobuf:

...
oneof foo {
  uint32 bar = 1;
  uint32 baz = 2;
}
...

Generated mapper code for this:

o1.setBar( o.getBar() );
o1.setBaz( o.getBaz() );

But only one should be set. With the proposed conditional mapping I could write a condition to check the case-Field of the source to find out which property should be set.

Example for the usage of the proposed feature

Mapper interface

@Mapping(target="baz", condition="java( bar.getBaz()==42 )")
Foo mapFoo(Bar bar);

Generated mapping code for property "baz"

if(bar.getBaz()==42) {
  foo.setBaz( bar.getBaz() );
}

If you are open to adopt this feature I would provide a PR.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions