A default constructor is a no-argument constructor that allows an object to be created without supplied arguments. Hibernate and JPA require one for every persistent class. If no constructor is declared, Java supplies a default constructor. section 3.2.3
For persistence-capable classes, the constructor has practical visibility and lifecycle constraints:
- Hibernate invokes the constructor through Java reflection when creating instances. section 3.2.3
- The constructor need not be public, but it must be at least package-visible for runtime-generated proxies. section 3.2.3
- An explicit parameterized constructor does not replace the required no-argument constructor; declare both when application code needs arguments. section 20.2
Entity with generated and application constructors
An entity can expose a no-argument constructor for persistence and a parameterized constructor for normal application use: @Entity @NoArgsConstructor public class User { private String name; public User(String name) { this.name = name; } } section 20.2
Listing 20.3 The User class
Path: Ch20/1 spring testing/src/main/java/com/manning/javapersistence /testing/model/User.java @Entity @NoArgsConstructor public class User { @Id @GeneratedValue @Getter private Long id; @NotNull @Size( min = 2, max = 255, message = "Name is required, maximum 255 characters." ) @Getter @Setter private String name; public User(String name) { this.name = name; } }
Inspect a complete entity showing @NoArgsConstructor alongside generated identity, validation, accessors, and an application-facing constructor. section 20.2


