Kotlin, mapstruct and generated DTO error "does not have an accessible parameterless constructor."

Viewed 5350

I am trying to use mapstruct to convert my complex dtos on my kotlin project.

mapstruct : 1.3.1.final kotlin: 1.3.71 openapi generator: 4.2.3

For example, i want to convert from a simple object to TestObjectDTO

    @Mapping(source = "mydescription",  target = "description")
    fun convertToDto(dto: TestObject): TestObjectDTO

I use OpenApi to generate my DTO : yaml

components:
  schemas:
    TestObject:
      title: TestObject
      description: ''
      type: object
      properties:
        mode:
          type: string
        description:
          type: string
      required:
        - mode
        - description

generated DTO

/**
 * 
 * @param mode 
 * @param description 
 */
data class TestObjectDTO (

        @get:NotNull 
        @JsonProperty("mode") var mode: kotlin.String,

        @get:NotNull 
        @JsonProperty("description") var description: kotlin.String
) {

}

A always have an error, because my constructor does not permit parameterless.

Did you have any idea how to fix this?

3 Answers

You can instantiate the DTO class manually using @ObjectFactory. The problem is that TestObjectDTO does not accept nulls, so you will need to use dummy values, which is not that pretty:

@Mapper
interface TestObjectMapper {

    @ObjectFactory
    fun createDto() = TestObjectDto("", "")

    @Mapping(source = "mydescription",  target = "description")
    fun convertToDto(dto: TestObject): TestObjectDto
}

1.3.1.Final does not support using constructors to create your objects. You will have to define a parameter less constructor as the error message says.

However, you can try 1.4.0.Beta3 that adde support for mapping using constructors. And this works with Kotlin data classes

In Java

A possible solution for this is to annotate the dto class with @NoArgsConstructor, for example:

@NoArgsConstructor
public class MyClass {
    private String myString;
    private Int myInt;
}
Related