Search code examples
javaspringspring-bootspring-data-jpaentity

When do I need constructor in an Spring entity?


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);
    }
}

Solution

  • 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");