liveBook · Manning

Default constructor

As explained in Java Persistence with Spring Data and Hibernate epub

A no-arg constructor is a constructor that accepts no parameters and can create an instance without supplied arguments.

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

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains reflection, visibility, and proxy implications, but does not detail constructor invocation internals.
Examples
Uses User and Log entities with Lombok-generated no-argument constructors and explicit constructors accepting domain values.
What it assumes
Assumes basic Java classes and constructors, while establishing the persistence requirement from the entity model.
What you can do after
Builds persistence-capable entities with framework-compatible constructors while retaining convenient application constructors.
How it connects
Connects default constructors with JPA entities, Hibernate reflection, runtime proxies, and entity lifecycle.

Also explained in

Compare how 3 books explain default constructor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.