Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    ER-GAIBI
    @ER-GAIBI
    Hello, Can we use methods of a final class and inject them on the mapper interface ? If yes, can you send a documentation or an example ?
    2 replies
    Zane XiaoYe
    @Zane-XY
    Hi, I found Mapstruct supports the Map<String, ???> to Pojo conversion. Is it possible to make available for some Map like interfaces like avro GenericRecord?
    public interface GenericRecord extends IndexedRecord {
      /** Set the value of a field given its name. */
      void put(String key, Object v);
    
      /** Return the value of a field given its name. */
      Object get(String key);
    }
    1 reply
    Jason Bodnar
    @Blackbaud-JasonBodnar
    If I have a class Entity that I want to map to Request and Request has a field Person person and I need to create Person from several fields in Entity (ie, entity.name, entity.address, entity.email ...) what's the best way to accomplish this?
    6 replies
    Jason Bodnar
    @Blackbaud-JasonBodnar

    If I have an enum:

    public enum TransactionSource {
        UNKNOWN(-1),
        CARD_NOT_PRESENT(0),
        CARD_PRESENT(1),
        CARD_PRESENT_KIOSK(2),
        STORE_CARD(3),
        UPDATE_CARD(4),
        MOBILE(5),
        DIRECT_DEBIT(6),
        SMART_CARD(7),
        STORE_DIRECT_DEBIT(8),
        UPDATE_DIRECT_DEBIT(9);
    
        public final int value;
    
        TransactionSource(int value) {
            this.value = value;
        }
    
        @JsonValue
        public int getValue() {
            return value;
        }
    }

    And I always want my mapper to set a field to TransactionSource.DIRECT_DEBIT is there a way to do that with the @Mapping(constant = ...)?

    @Mapping(target = "source", constant = TransactionSource.DIRECT_DEBIT)

    Gives me an error because constant must be a String.

    3 replies
    Jason Bodnar
    @Blackbaud-JasonBodnar

    When using @MappingTarget to update an existing bean is there a flag to tell MapStruct not to update non-null fields on the bean?

    IE, if @MappingTarget PersonEntity person has a field fullName already set to Jason Bodnar and Person person has fullName set to John Doe I'd prefer to keep Jason Bodnar.

    10 replies
    Mohamad Tahawi
    @mhdtahawi

    Hello,

    I would love to get your help on this question: https://stackoverflow.com/questions/71204015/mapstruct-using-same-mapper-for-all-enums

    In a nutshell, I have a class EnumDTO and I would like to map all my enums to this class, with the same logic for all enum types.
    Is there anyway to tell MapStrucy "If it is an Enum to EnumDTO, use this method" ?

    5 replies
    bsk-123
    @bsk-123
    I'm trying to create a custom mapping using @Aftermapping in mapper interface in kotlin but the @Aftermapping is being generated as a mapping in autogenerated code

    @Mapper(
    builder = Builder(disableBuilder = true),
    componentModel = "jsr330",
    nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT,
    uses = [MapstructMapper::class],
    injectionStrategy = InjectionStrategy.CONSTRUCTOR
    )
    interface StudentToTeacherMapper {

    @Mappings(
    Mapping(source = "studentId", target = "teacherId")
    )
    fun toTeacher(student : Student) : Teacher

    @AfterMapping
    fun fill(@MappingTarget teacher : Teacher, student:Student){
    teacher.setStatus("Teacher");
    }
    }

    bsk-123
    @bsk-123
    But in the auto generated code the aftermapping method is called in toTeacher() but also created a mapper like this
    public void fill(Teacher teacher, Student student){
    teacher.setName(student.getName())
    ........
    fill(teacher,student)
    }
    calling again the function recursively but i dont want this to happen what should i do please helpppp
    2 replies
    Kadir Tuna
    @kadirtn

    Hi everyone, i have a custom case that some of my dto's have a field of type X, and i need to map this class to Y by using a spring service method call(i do a transactional db operation and return an instance of Y). But in this scenario i also need to use existing value of Y field. Let me explain it by example.

    // DTO
    public class AnnualLeaveRequest {
        private FileInfoDTO annualLeaveFile;
    }
    //ENTITY
    public class AnnualLeave  {
    
        @OneToOne
        private FileReference annualLeaveFile;
    }
    @Mapper
    public abstract class FileMapper {
        @Autowired
        private FileReferenceService fileReferenceService;
    
        public FileReference toFileReference(@MappingTarget FileReference fileReference, FileInfoDTO fileInfoDTO) {
            return fileReferenceService.updateFile(fileInfoDTO, fileReference);
        }
    }
    //ACTUAL ENTITY MAPPER
    @Mapper(uses = {FileMapper.class})
    public interface MazeretIzinMapper {
        AnnualLeave toEntity(AnnualLeaveRequest dto);
    }
    // WHAT IM TRYING TO ACHIEVE
    @Component
    public class MazeretIzinMapperImpl implements tr.gov.hmb.ikys.personel.izinbilgisi.mazeretizin.mapper.MazeretIzinMapper {
    
        @Autowired
        private FileMapper fileMapper;
    
        @Override
        public AnnualLeave toEntity(AnnualLeaveRequest dto) {
            AnnualLeave entity = new AnnualLeave();
            entity.setAnnualLeaveFile(fileMapper.toFileReference(dto.getAnnualLeaveFile(), entity.getAnnualLeaveFile()));
            return entity;
        }
    
        @Override
        public void updateEntity(AnnualLeave entity, AnnualLeaveUpdateRequest dto) {
            entity.setAnnualLeaveFile(fileMapper.toFileReference(dto.getAnnualLeaveFile(), entity.getAnnualLeaveFile()));
        }
    }

    But mapstruct ignores the result of "FileReference toFileReference(@MappingTarget FileReference fileReference, FileInfoDTO fileInfoDTO) " and does not map the result of it to the actual entity's FileReference field. Do you have any idea for resolving this problem?

    4 replies
    Jonas
    @Ditscheridou
    Hello, are there plans to support Kotlin Multiplatform ?
    1 reply
    lawdlop
    @lawdlop

    hello guys, please I have two POJOs Edition and EditionDto as shown below:

    public class Edition {
        private List<Round> rounds;
        private List<Stage> stages;
    }
    
    public class EditionDto {
        private List<RoundDto> rounds;
    }
    
    public class RoundDto {
       private List<StageDto> stages;
    }

    Is it possible to use mapstruct to
    transform from Edition to EditionDto? I am having difficulty transforming the two classes
    as RoundDto doesn't have stages directly.
    I tried this:

    @Mappings({@Mapping(source ="rounds", target= "rounds"),
                @Mapping(source ="stages", target = "entity.rounds.stages")
        })
    EditionDto map(Edition entity);

    but wasn't successful.

    1 reply
    monkmonah
    @monkmonah

    Hey, I'm using gradle-7.4.1 with:

        implementation "org.mapstruct.extensions.spring:mapstruct-spring-annotations:0.1.1"
        annotationProcessor "org.mapstruct.extensions.spring:mapstruct-spring-extensions:0.1.1"
        testAnnotationProcessor "org.mapstruct.extensions.spring:mapstruct-spring-extensions:0.1.1"

    And I'm getting:

    ...Mapper.java:14: error: cannot find symbol @Mapping

    I followed that tutorial https://mapstruct.org/documentation/spring-extensions/reference/html/
    What I'm missing?

    5 replies
    poxu
    @poxu
    Hello!
    I have a large object with many fields and a small object with two fields. And I set unmappedSourcePolicy = ReportingPolicy.ERROR . I want to map large object to small object and ignore most of the fields, large object has. For that, I am trying to use @Mapping(ignore = true) . But it requires to specify target. And I don't want to ignore any target fields. So, could you please tell me, how I could ignore fields, specifying source attribute only?
    1 reply
    KelvinMuller
    @KelvinMuller
    Please assist on this....I have not found a solution even after posting on stack overflow
    https://stackoverflow.com/questions/71765883/mapstruct-mapping-a-dto-in-a-dto-to-an-entity-in-an-entity
    Al Grant
    @bigal_nz_twitter
    Morning people
    I have a job that map struct might be able to help with

    I have a parent object (BIRD) that returns a list of children (PIT - a type of microchip).
    I then need to construct a DTO with fields like bird.name, bird,sex and PIT.code - where PIT.code is the newest PIT code based on PIT.insertDate.

    Currently using model mapper with some list filtering on the service

            //DRAFT
        @Override
        public BirdSummaryDTO getBirdSummaryDTOById(Long id) {
          Bird bird = this.get(id);
          BirdSummaryDTO birdSummaryDTO = new BirdSummaryDTO();
            ModelMapper mapper = new ModelMapper();
            birdSummaryDTO = modelMapper.map(get(id), BirdSummaryDTO.class);
            birdSummaryDTO.setPitCode(getNewestPitCode(bird));
            birdSummaryDTO.setLastHealthCheck(getNewestHealthCheckDate(bird));
            return birdSummaryDTO;
        }
    
        // RETURN NEWEST DATE OF HEALTH CHECK
        public LocalDate getNewestHealthCheckDate(Bird bird) {
            List<HealthCheck> listHealthCheck;
            listHealthCheck = bird.getListHealthCheck();
            HealthCheck newest = listHealthCheck.stream().max(Comparator.comparing(HealthCheck::getCatchDate)).get();
            return newest.getCatchDate();
        }
    
        // RETURN NEWEST PIT CODE FROM BIRD
        public String getNewestPitCode(Bird bird) {
            List<PIT> listPIT;
            listPIT = bird.getListPIT();
            PIT newest = listPIT.stream().max(Comparator.comparing(PIT::getDateInserted)).get();
            return newest.getCode();
        }
    does map struct help her?
    1 reply
    Jan Vissers
    @jvissers
    Hi - I'm new to mapstruct and I'm trying to get a CDI decorator going. But it seems that whatever I do, it doesn't seem like the correct sources are generated.
    So would appreciate some guidance. First of - do I need to include the decorator in the beans.xml file?
    1 reply
    Jan Vissers
    @jvissers
    image.png
    I get a null pointer in some Helidon MP code - not sure why.
    Al Grant
    @bigal_nz_twitter
    @Chessray thanks for your answer
    @Chessray but yes I did write the logic
    I have another question, if I have a entity Bird with say 20 fields.
    I have two views on my controller, one view is for a dashboard which only needs 4 fields of a list birds, but then another view to give an overview of a single bird which returns most of the 20 fields - I assume it would be normal to use two seperate bird DTOs and each bird DTO needs a seperate mapping class?
    7 replies
    Al Grant
    @bigal_nz_twitter

    I have a parent entity with a OneToMany to a child entity.
    In my DTO I would like to have a list of the children.
    I tried

    @Data
    public class BirdViewDTO {
        private Long id;
        private String name;
        private String status;
        private LocalDate dateDeceased;
        private String sex;
        private String taxa;
        private String comment;
    
        private LocalDate dateLastHealthCheck;
        private String pitCode;
        private Integer channel;
        private Double channelOffset;
    
        private List<Weight> listWeights = new ArrayList<>();

    But without further configuration MapStruct doesn't map this

    How could my entity return a list of Weight with all weights fields? What about selected fields from Weight?
    Al Grant
    @bigal_nz_twitter

    One other thing that is messing with me.
    Lets say you have a entity

    @Data 
    public class BirdDTO {
        private Long id;
        private String name; //bird name
        private List<HealthCheck> listHealthCheck;
    }

    and then on HealthCheckDTO

    @Data 
    public class HealthCheckDTO {
        private Long id;
        private String name; //bird name

    The issue I am facing is that if I want a DTO for a healthcheck, I have included the name of the bird
    But if I bring a bird back with a list of healthchecks I dont want the bird name in the list of health checks because i already have it

    Its almost like I need another DTO, one for HealthCheck on its own (including bird name) and a seperate DTO for healthcheck when its used with a bird DTO
    Jan Vissers
    @jvissers
    Are there any examples that define a MapStruct mapper interface that extends a generic interface.
    Like: interface MyMapper<DTO, E> { List<DTO> entityToDTO(E entity); }
    Al Grant
    @bigal_nz_twitter
    Di you create a mapper class for each view of an etity, like MapperViewEntity and MapperDashboard entity, or a single class with different methods for the various views?
    1 reply
    Al Grant
    @bigal_nz_twitter
    Does @AfterMapping apply to every method on the class?
    2 replies
    Al Grant
    @bigal_nz_twitter
    I am trying to pass in two obejcts to map struct and what was working now fails https://stackoverflow.com/questions/71923245/mapstruct-passing-in-multiple-objects-error
       @Mapping(source = "bird.name", target = "name")
        @Mapping(source = "location.x", target = "latitude")
        @Mapping(source = "location.y", target = "longitude")
        HealthCheckViewDTO healthCheckToHealthCheckViewDTO(HealthCheck healthCheck, Transmitter transmitter);

    with

    error: Method has no source parameter named "bird". Method source parameters are: "healthCheck, transmitter".
        HealthCheckViewDTO healthCheckToHealthCheckViewDTO(HealthCheck healthCheck, Transmitter transmitter);

    Yet it works fine with one paramter

    3 replies
    It should still find bird which (A) was working prior to transmitter and (b) is a parent on HealthCheck
    hakil
    @hakil
    Hello everyone,
    I have a strange problem, Mapstruct prompts me that there is no property, I am sure this property exists, and it has a Get method.
    It's bugging me so much, I can't solve this problem, please help me.
    4 replies
      public static interface UniqueId {
            String getUniqueId();
        }
    
        public static abstract class AbsUser<T extends UniqueId>{
            @Getter
            protected final UniqueId uniqueId;
    
            protected AbsUser(UniqueId uniqueId) {
                this.uniqueId = uniqueId;
            }
        }
    
        public static class User extends AbsUser<User.UserId>{
    
            protected User(UniqueId uniqueId) {
                super(uniqueId);
            }
    
            public static class UserId implements UniqueId{
                private final String id;
    
                public UserId(String id) {
                    this.id = id;
                }
    
                @Override
                public String getUniqueId() {
                    return id;
                }
            }
        }
        @Data
        public static class UserA{
            private String id;
        }
        @Mapper
        public static interface Convert{
            public static final Convert INSTANCE= Mappers.getMapper(Convert.class);
            @Mapping(target = "id", source = "uniqueId.id")
            public UserA to(User user);
        }
    11 replies
    Alex
    @a-zen

    Hi,

    we are using MapStruct with Gradle. Is there a way to configure these so that the annotation processing is also done for classes in the test package? We have written a Mapper that we only want to use for our tests, but unfortunately the MapperImpl is not generated. As soon as we move the mapper to the main package it works.

    3 replies
    MOHAMD DORRA
    @mhddurrah
    Hello, I am getting "Attempt to recreate a file for type intellij"
    IntelliJ 2021 and 2022
    niklas
    @niklas:matrix.niklasfi.de
    [m]
    Hi, I have a project that is using mapstruct(spring initialization) + lombok + xmlbeans. mapstruct + lombok seems to be a solved problem with the lombok-mapstruct-binding as annotationProcessor in maven-compiler plugin. Now the fun starts when xmlbeans gets added to the equation. xmlbeans is a library that generates java classes (to generated-sources) from given xsd files. Unfortunately, on second invocation of mvn compile I always get /home/niklas/pwc-dev/pta/mapstruct-xmlbeans/src/main/java/CarMapper.java:[6,8] Internal error in the mapping processor: java.lang.RuntimeException: javax.annotation.processing.FilerException: Attempt to recreate a file for type CarMapperImpl at org.mapstruct.ap.internal.processor.MapperRenderingProcessor.createSourceFile(MapperRenderingProcessor.java:59) ... which I think was also the issue that lead to the creation of the annotation processor. My question: Would someone know how to 1. debug this? 2. Would someone have any hints on how to write a similar annotation processor for xmlbeans? 3. What does the Hider which I think is the fix for the issue in the lombok + mapstruct case actually do https://github.com/projectlombok/lombok/commit/0d7540db0cc0c9a2758799522925f09eddeb7420#diff-591c69d7e005db80dff9bb023a05e118b7dea861584cb8fe35439a49f326a397 ? I would really appreciate any hints pointing me in the right direction, even if don't fully solve the issue. I would also be willing to submit my results afterwards so other people with the same library combination don't have to go through this themselves
    1 reply
    niklas
    @niklas:matrix.niklasfi.de
    [m]
    Hi Filip, thank you for looking into this. An interesting point. I was indeed always looking at the generated sources and not the generated resources folder although I am pretty sure that it does not touch /annotations
    niklas
    @niklas:matrix.niklasfi.de
    [m]
    @filiphr: Just checked. Are you positively talking about generated-REsources? There is no annotations folder in generated-resources. There is one in generated-sources, however
    I have just set up a minimal reproducible example to demonstrate the issue I am having
    2 replies
    niklas
    @niklas:matrix.niklasfi.de
    [m]
    @Zegveld: I have uploaded the code here: https://github.com/niklasfi/mapstruct-xmlbeans it would really be great if you could have a look.
    1 reply
    Andrey Avtomonov
    @andreybavt

    Hi! Could someone help me understand how to ignore abstract parent property mapping in one place and not for every child class?
    I have the same sutiation as described here: https://gitter.im/mapstruct/mapstruct-users?at=5e15cac4e0f13b70c95140ee

    and I'd like to ignore createdAt, modifiedAt at one place for any class inheriting from AbstractAuditingEntity

    1 reply
    niklas
    @niklas:matrix.niklasfi.de
    [m]
    @Zegveld: wow, thank you so much for your effort. I will test this immediately and get back to you.