mapstruct / mapstruct/mapstruct

Conditional mapping by group

Open
#3,843 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Java
Stars
7.7k
Forks
1.1k
PR merge metrics
No merged PRs in 30d

Description

Use case

Can we have a specific annotation for conditional mapping?

class PersonDto {

    @MapOn({
            ValidationGroup.Create.class
    })
    @NotBlank({
            ValidationGroup.Create.class
    })
    private String name; // not gonna changed once inserted

    @MapOn({
            ValidationGroup.Create.class,
            ValidationGroup.Update.class
    })
    @NotBlank({
        ValidationGroup.Create.class,
        ValidationGroup.Update.class
    })
    private String address; // may be updated whenever moved
}
class PersonEntity {

    @Column(name = "name", nullable = false, insertable = true,
        updatable = false // <<<<<<<<<<<<<<<<<<<<<<<<<<<
    )
    private String name;

    @Column(name = "address", nullable = false, insertable = true, 
        updatable = true // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    )
    private String address;
}
public interface _BaseEntityTypeMapper<T extends _BaseEntityType<T>, U extends _BaseEntity<U>>
        extends __BaseTypeMapper<T> {

    U mapToEntity(T source, @MappingTarget U target, Class<?>... groups);

class PeopleController {

    void create(@Validated(ValidationGroup.Create.class) PersonDto personDto) {
        // maps name and address
        PersonEntity entity = personMapper.mapToEntity(personDto, new PersonEntity(), ValidationGroup.Create.class);
    }

    void update(@Validated(ValidationGroup.Update.class) PersonDto personDto) {
        PersonEntity personEntity = findById(0L);
        // maps `address` only
        PersonEntity entity = personMapper.mapToEntity(personDto, personEntity, ValidationGroup.Update.class);
    }
}
Generated Code

No response

Possible workarounds

No response

MapStruct Version

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the @MapOn examples and the _BaseEntityTypeMapper.mapToEntity entry point, including its Class<?>... groups parameter. Define how mapping should differ for Create and Update groups, then verify that name maps only on create while address maps on both operations; the issue names no files or tests to run.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.