openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[BUG][JAVA][SpringCodegen] Inheritance copyOf() results in null parent attributes

Open marvinsommer opened this issue 1 year ago • 0 comments

Description

Using inheritance via the normalizer setting

REF_AS_PARENT_IN_ALLOF

together with Builder generation, yields the following code for toBuilder methods

public Dog.Builder toBuilder() {
    Dog.Builder builder = new Dog.Builder();
    return builder.copyOf(this);
}

copyOf looks like this

protected Builder copyOf(Dog value) { 
    super.copyOf(instance);
    this.instance.setIsGoodBoy(value.isGoodBoy);
    return this;
}

Since super.copyOf(instance) is called instead of super.copyOf(value) we loose all set parent model values. instance is a fresh object without set values since the constructor was called in the .toBuilder() call.

public Builder() {
    this(new Dog());
}

protected Builder(Dog instance) {
    super(instance); // the parent builder shares the same instance
    this.instance = instance;
}

Instead the copyOf method should look like this to retain all parent model values:

protected Builder copyOf(Dog value) { 
    super.copyOf(value);
    this.instance.setIsGoodBoy(value.isGoodBoy);
    return this;
}
openapi-generator version

@Generated(value = "org.openapitools.codegen.languages.SpringCodegen", date = "2024-08-22T10:43:42.285171+02:00[Europe/Berlin]", comments = "Generator version: 7.7.0")

Issue still persists in 7.8.0, since related .mustache file is still the same.

modules/openapi-generator/src/main/resources/JavaSpring/javaBuilder.mustache

Generated file example: Dog.java

OpenAPI declaration file content or url

Dog.yml

Generation Details

Builder Pattern generation enabled

Normalizer settings: REF_AS_PARENT_IN_ALLOF

marvinsommer avatar Aug 22 '24 09:08 marvinsommer