27

I have seen multiple codes online on applications of Spring Boot in IntelliJ, and many use both @AllArgsConstructor and @NoArgsConstructor together and both are constructors however the purpose of each is different -

  • @AllArgsConstructor generates a constructor requiring argument for every field in the annotated class
  • @NoArgsConstructor generates a constructor with no parameter

Then why are we using both together over the same entity and how do they function in such case?

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Entity
public class Product {
    @Id
    private int id;
    private String name;
    private String type;
}
Yann39
  • 14,285
  • 11
  • 56
  • 84
NIKITA RATH
  • 354
  • 1
  • 3
  • 12
  • 12
    You need a default constructor (constructor without any argument) in entities. This is needed because JPA/Hibernate uses the default constructor method to create a bean class using reflections. If you don't specify any constructor (nor Lombok annotation), Java will generate a default constructor (automatically generated by the compiler if no constructors have been defined for the class). But if you add a constructor with parameters (or `@AllArgsConstructor`), then you'll need to add a no args constructor (or `@NoArgsConstructor`) as well, for JPA/Hibernate to work. – Yann39 Jul 09 '21 at 09:10
  • @Yann39 Ok, I get that. Now, I declared `@AllArgsConstructor`. But why won't JPA work without declaring `@NoArgsConstuctor` for the same ? – NIKITA RATH Jul 09 '21 at 09:59
  • 4
    Because Java will generate a default contructor only if there are no constructors defined for the class. As soon as you define one, it will not generate the no args constructor. Also note that you are using `@Data`, which bundles the features of `@RequiredArgsConstructor`, which will generate a constructor for all final or `@NonNull` annotated fields. So as you are using only non final nullable fields, it may generate an empty constructor even if you don't add `@NoArgsConstructor`. I have not tested that last case though. – Yann39 Jul 09 '21 at 10:13
  • Ok got it now that's clear, thank you – NIKITA RATH Jul 09 '21 at 10:21
  • Good. I posted as comment because I had no time for writting a clean answer right now, but I can post a more elaborated answer later. – Yann39 Jul 09 '21 at 10:44

2 Answers2

16

The JPA specification requires that all persistent classes (@Entity) have a no-arg constructor, public or protected. (note that this is not necessarily true when dealing with some implementation like Hibernate, see this answer).

This is needed because JPA uses the default constructor method to create a bean class using the reflection API. Indeed if your class would contain many constructors then JPA wouldn't know which one to call, this is why it instantiates the class through its no-arg constructor using reflections :

Product.class.newInstance();

which is equivalent to new Product() (Product.class is a class literal, it can fail at runtime if the class is not found in the classpath), then, once instantiated, uses fields setters to deal with it.

Then, in Java, a default constructor (no-argument constructor) is automatically generated for a class unless you define other constructors (it only does when you don't provide any other constructor).

So because the compiler automatically creates a default no-arg constructor when no other constructor is defined, only classes that define constructors must also include a no-arg constructor if required by a framework (here JPA). This is why you need to add @NoArgsConstructor annotation if you add the @AllArgsConstructor annotation.

Also note that you are using @Data, which bundles the features of @RequiredArgsConstructor, which will generate a constructor for all final or @NonNull annotated fields (see Lombok documentation). So as you are using only non final nullable fields, it may generate an empty constructor even if you don't add the @NoArgsConstructor annotation. I have not tested that last case though, I know that it generates an empty constructor when using @RequiredArgsConstructor directly with non final nullable fields, but I don't know if it works the same when using @Data.

@Data also bundles @ToString, so you don't need to add it again.

I'm personnaly not a fan of using @Data if I don't need all the bundled annotations, so I usually simply use :

@Entity
@Getter
@Setter
@EqualsAndHashCode
public class Product {

    @Id
    private int id;

    private String name;

    private String type;

}

as I often don't use toString() nor parameterized constructor. It may be more verbose but more meaningful to me.

Yann39
  • 14,285
  • 11
  • 56
  • 84
13

These are the annotations from Lombok. To understand why it's is needed you have to understand how things work internally.

JPA says
It's specification says "The JPA specification requires that all persistent classes have a no-arg constructor. This constructor may be public or protected. Because the compiler automatically creates a default no-arg constructor when no other constructor is defined, only classes that define constructors must also include a no-arg constructor."

To understand further, when it creates and entity using reflection it uses Class.newInstance() method which requires a no-argument constructor to create an instance.

The most common type of dependency injection used by Spring is

  1. Constructor based Injection
  2. Setter based Injection

Constructor based Injection (@AllArgsConstructor): When you create object by passing all parameters, you basically use a constructor injection. It should be done when we have all parameter values and we want to create an object with all values initialized.@AllArgsConstructor generates a constructor requiring an argument for every field in the annotated class.

Setter based Injection (@NoArgsConstructor): We create an object first (uses no arg-constructor) and then update the dependencies or values later by using setters.@NoArgsConstructor generates a default constructor with no parameters.

There are many key differences between constructor injection and setter injection.

  • Partial dependency: can be injected using setter injection but it is not possible by constructor. Suppose there are 3 properties in a class, having 3 arg constructor and setters methods. In such case, if you want to pass information for only one property, it is possible by setter method only.

  • Overriding: Setter injection overrides the constructor injection. If we use both constructor and setter injection, IOC container will use the setter injection.

  • Changes: We can easily change the value by setter injection. It doesn't create a new bean instance always like constructor. So setter injection is flexible than constructor injection.

@NoArgsConstructor will generate a constructor with no parameters. If this is not possible (because of final fields), a compiler error will result instead, unless @NoArgsConstructor(force = true) is used, then all final fields are initialized with 0 / false / null. For fields with constraints, such as @NonNull fields, no check is generated,so be aware that these constraints will generally not be fulfilled until those fields are properly initialized later. Certain java constructs, such as hibernate and the Service Provider Interface require a no-args constructor. This annotation is useful primarily in combination with either @Data or one of the other constructor generating annotations.

@AllArgsConstructor generates a constructor with 1 parameter for each field in your class. Fields marked with @NonNull result in null checks on those parameters.

Conclusion:

  • @AllArgsConstructor generates a constructor requiring an argument for every field in the annotated class.
  • @AllArgsContstructor also allows the creation of static factory methods using the staticName attribute
  • @NoArgsConstructor generates a default constructor with no parameters
  • @NoArgsConstructor can create a static factory method for construction purposes
  • Lombok can't call the super constructor unless it has a no-args constructor
  • If the superclass doesn't have a no-args constructor, Lombok can't generate any constructor in the subclass
TriS
  • 3,668
  • 3
  • 11
  • 25