JoeG
JoeG

Reputation: 7652

Lombok: generated constructor missing?

For this code:

@Data
@Entity
@AllArgsConstructor
public class Person {

    private @GeneratedValue @Id Long id;
    private final String firstname;
    private String middlename;
    private final String lastname;
}

Lombok (v. 1.16.14) should generate two constructors. First, due to the @Data:

public Person(String firstname, String lastname) { ... }

Due to the @AllArgsConstructor, there should also be:

public Person(Long id, String firstname, String middlename, String lastname);

However, the first (two parameter) constructor "disappears" when adding the @AllArgsConstructor annotation. The javadoc for @Data states:

Equivalent to @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode.

So am I wrong thinking the two argument ctor should be there? This has a very simple workaround because if the @RequiredArgsConstructor annotation is explicitly added:

@Data
@Entity
@AllArgsConstructor
@RequiredArgsConstructor
public class Person {

    private @GeneratedValue @Id Long id;
    private final String firstname;
    private String middlename;
    private final String lastname;
}

both ctors are available. However, this behavior makes little to no sense to me, so I was hoping someone might explain if this is a bug or a feature!

Upvotes: 3

Views: 6010

Answers (1)

Roel Spilker
Roel Spilker

Reputation: 34562

@Data only generates constructors if there are none.

The documentation says: "@Data is like having implicit @Getter, @Setter, @ToString, @EqualsAndHashCode and @RequiredArgsConstructor annotations on the class (except that no constructor will be generated if any explicitly written constructor exists)." Your @AllArgsConstructor counts as an explicitly written contructor.

This is a feature.

Disclosure: I am a Lombok developer.

Upvotes: 11

Related Questions