mkarneim / pojobuilder

A Java Code Generator for Pojo Builders
Other
334 stars 44 forks source link

@GeneratePojoBuilder and inheritance-depth #103

Closed flexguse closed 7 years ago

flexguse commented 9 years ago

Hi,

first of all thanks a lot for PojoBuilder, it helps me a lot in by day-to-day business.

Currently I'm setting up a new project using pojo-builder in version 3.4.0 and Java 1.8 with a multi inheritance object modeling like

public abstract class AbstractEntity{}

public abstract class LocalizedEntity extends AbstractEntity{}

public abstract class CatalogEntity extends LocalizedEntity{}

@GeneratePojoBuilder
public class Article extends CatalogEntity{}

The generated builder for Article (ArticleBuilder) only includes the attributes of CatalogEntity but not of LocalizedEntity or AbstractEntity.

Did I miss something in the configuration? Is this maybe not a feature of PojoBuilder? Has this question asked a hundret times and I'm not able to find the answer?

Please help!

Thank you in advance, Christoph

mkarneim commented 9 years ago

Christoph,

PB is perfectly fine with inheritance hierarchies. Just make sure, that PB has write access to all properties of your pojo.

For example, place the @GeneratePojoBuilder above the pojo's constructor if it has parameters, instead of placing it above the class declaration.

Here is a working example:

public class AbstractEntity<ID> {
  private ID id;
  private DateTime created;

  public AbstractEntity(ID id, DateTime created) {
    this.id = id;
    this.created = created;
  }

  public ID getId() {
    return id;
  }

  public DateTime getCreated() {
    return created;
  }
}

public class Product extends AbstractEntity<Long> {

  private String name;

  @GeneratePojoBuilder
  public Product(Long id, DateTime created) {
    super(id, created);
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

public class ProductBuilderTest {

  @Test
  public void testBuild() {
    // Given:
    Long id = Long.valueOf(1);
    DateTime dateTime = DateTime.now();
    String name = "xyz";
    ProductBuilder underTest = new ProductBuilder();

    // When:
    Product actual = underTest.withId(id).withCreated(dateTime).withName(name).build();

    // Then:
    assertThat(actual.getId()).isEqualTo(id);
    assertThat(actual.getCreated()).isEqualTo(dateTime);
    assertThat(actual.getName()).isEqualTo(name);
  }
}