3

I’m starting my very first steps with Mapstruct mapper. I want to map a JPA data entity class to a DTO class. This is my source class:

@Entity
@Data
@Table(name = "projects")
public class Project {
    @Id
    private Long Id;
    private String projectName;
    private String description;

    @OneToMany(mappedBy = "project")
    List<Sprint> sprints;

    @OneToMany(mappedBy = "project")
    List<Epic> epics;

    @OneToMany(mappedBy = "project")
    List<Story> stories;

    public Project(Long id, String projectName, String description) {
        Id = id;
        this.projectName = projectName;
        this.description = description;
    }
}

This is my target class:

@Data
@AllArgsConstructor
public class ProjectDTO {
    private Long Id;
    private String projectName;
    private String description;
}

The @Data annotation is from Lombok. I want to make a mapper to map the Project to ProjectDTO, the attributes like sprints, epics, stories SHOULD NOT be included in ProjectDTO. This is my mapper interface:

@Mapper
public interface ProjectMapper extends Mapper {

    ProjectMapper INSTANCE = Mappers.getMapper(ProjectMapper.class)

    ProjectDTO projectToProjectDTO(Project project);
}

When I try to build it, this is the error message I got:

[ERROR] Can't generate mapping method with no input arguments.

I guess it’s related to the missing properties in ProjectDTO, but don’t know to solve it. With the @Mapping, I cannot do it like:

@Mapping(source=“sprints”, target= null)

Any help would be appreciated!

3 Answers 3

1

Add the '@NoArgConstructor' as well. MapStruct cannot (yet) deal with constructing objects via constructor. Another option would be using '@Builder' in stead if your objects are truly immutable

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your comment, it doesn't work in my case. Some how I found the solution by get the mapper instance in my ProjectServiceImpl constructor. I will put it here also as an answer
0

You should not extend the annotation Mapper. It is enough when you just use it at the type declaration level of your interface

Comments

0

Had the same issue recently with springboot My solution was:

Create a mapper config

@org.mapstruct.MapperConfig(
        unmappedTargetPolicy = ReportingPolicy.IGNORE,
        componentModel = "spring"
)
public interface MapperConfig {
}

Then use it like this in one of your mapper classes.

@Mapper(
        config = MapperConfig.class
)
public abstract class MyClassMapper...

Hope it helps someone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.