ignore fields from target class which isn't in target class. MapStruct

388 Views Asked by At

I have a problem with mapping fields from through MapStruct.

I have two classes. First domain class "Event" for example with fields

1) id
2) lastUpdate
2) type
3) participants
4) description

And Second class is "EventForm". EventForm have fields:

1) type
2) participants 
3) description

And when I want to update an existing event, the following happens: 1) I get an existing event from database by Id

Event event = eventService.get(id);

And event have id = 10000, lastUpdate=11213123123;

2) I am mapping fields from form to a domain class

event = mapper.eventFormToEvent(eventForm)

3) After that event has NULL value in id and lastUpdate values.

How ignore all unmapped fields in target class?

I will specify that I need all unmapped fields ignore, not one by one

1

There are 1 best solutions below

0
On BEST ANSWER

What you are looking for is updating bean instances. This is what you will need to use for your use case. It uses the @MappingTarget annotation.

Your mapper will look like:

@Mapper
public interface MyMapper {

    void update(@MappingTarget Event event, EventForm eventForm);
}

or:

@Mapper
public interface MyMapper {

    Event update(@MappingTarget Event event, EventForm eventForm);
}

In the second case, MapStruct, just returns the passed event back. You will have to keep in mind that the parameter passed for @MappingTarget must not be null.