Home > database >  When do I need constructor in an Spring entity?
When do I need constructor in an Spring entity?

Time:12-10

I am new in Spring and now working a Java project based on Spring Boot. When I was using Entity Framework, I have seen a similar usage that is used for lazy-loading. But I am not sure if it is true for Spring Framework. Could you pls clarify me why constructor is used for some of Entity classes in Spring?

public class Employee extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "employee_gen")
    private long id;

    @Column(nullable = false)
    private String name;


    public Employee(
            @Nonnull String name
    ) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return super.equals(other);
    }
}

CodePudding user response:

A purpose behind declare constructor is to initialize the data fields of objects in the class. constructors are work like a gatekeepers of object-oriented design

Why using constructor in spring boot

  • create a constructor with all required fields of the entity

  • Reason: A constructor should always leave the instance created in a same state.

CodePudding user response:

If you want to set value in the fields and don't want to do using a getter setter then simply you can pass the value as a constructer so that it will automatically initialize the object;

Otherwise, you have to do like this

Without constructor

Employee emp = new Employee ();
emp.setName("ex");

With constructor

Employee emp = new Employee ("ex");
  • Related