Skip to content

QOL improvement with @PrimaryMappingSource instead of explicit source declaration #3161

@lbenedetto

Description

@lbenedetto

Use case

Sometimes, a mapping needs to borrow a field from another table.

@Mapping(target = "borrowed", source = "tblB.borrowed")
EntityA toEntity(TblA tblA, TblB tblB)

But if those tables have many similar fields, then we'll get lots of errors

error: Several possible source properties for target property "id"
error: Several possible source properties for target property "name"
error: Several possible source properties for target property "description"
error: Several possible source properties for target property "createdAtUtc"
error: Several possible source properties for target property "updatedAtUtc"

which can be resolved by manually specifying the source of every conflicting property

@Mapping(target = "id", source = "tblA.id")
@Mapping(target = "id", source = "tblA.name")
@Mapping(target = "id", source = "tblA.description")
@Mapping(target = "id", source = "tblA.createdAtUtc")
@Mapping(target = "id", source = "tblA.updatedAtUtc")
@Mapping(target = "borrowed", source = "tblB.borrowed")
EntityA toEntity(TblA tblA, TblB tblB)

My proposal is a new annotation called something like @PrimaryMappingSource which would be used like this

@Mapping(target = "borrowed", source = "tblB.borrowed")
EntityA toEntity(
  @PrimaryMappingSource TblA tblA, 
  TblB tblB
)

Which would have the effect of defaulting to tblA when there is any ambiguity in the source for a target property. This is similar to the @org.springframework.context.annotation.Primary annotation, which they explain like this:

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.

Generated Code

The generated code would be the same as manually specifying the source of all those ambiguous properties

Possible workarounds

No response

MapStruct Version

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions