Search code examples
javalombok

java error : constructor is already defined in class - using lombok


The error

java: constructor Restaurant() is already defined in class  
com.example.order_system.domain.Restaurant

appear when I add this class and run the program

@Entity
@NoArgsConstructor
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public class Restaurant {

    @Id
    @GeneratedValue
    private long id;

    @NotEmpty(message = "The restaurant must have a name")
    private String name;

    @NotEmpty(message = "Please add a description for this restaurant")
    private String description;

    @NotEmpty(message = "The restaurant must have a location")
    private String location;

    @OneToMany(mappedBy = "restaurant", fetch = FetchType.EAGER)
    private List<ContactDetails> contactDetails = new ArrayList<>();

}

Solution

  • As mentioned in documentation @RequiredArgsConstructor is built using final fields:

    @RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared. For those fields marked with @NonNull, an explicit null check is also generated. The constructor will throw a NullPointerException if any of the parameters intended for the fields marked with @NonNull contain null. The order of the parameters match the order in which the fields appear in your class.

    So either remove @RequiredArgsConstructor annotation or mark some of fields with final keyword (or @NonNull annotation).