Home > Back-end >  Is it mandatory to use no args constructor using @entity annotation in java spring boot?
Is it mandatory to use no args constructor using @entity annotation in java spring boot?

Time:09-17

I am working on a spring boot application (v2.1.5.RELEASE) with h2 as an in-memory database. I created a simple project with a main and only one model Person.java with just 3 private fields. I have no constructor at all but when I launch the application and open the h2 console, I am still able to see the table created from the entity Person. I read from a enter image description here

CodePudding user response:

Java implicitly adds a no-arg constructor to all classes when there is no constructors defined. If you define any parameterized constructor then the no-arg constructor will not be added.

According to the other SO question, it is mandatory to have no-arg constructor for initialization of the entities.

So the behavior is perfect here.

CodePudding user response:

The creation of schema has nothing to do with the Java constructor. Spring and ORM vendors can read java fields using reflection, and also consider meta-information provided from annotations.

Constructor is just used to create java instances.

I have no constructor at all but when I launch the application and open the h2 console, I am still able to see the table created from the entity Person

The table is created from all the info, that I have mentioned above. Nothing to do with constructors

As for your second question

a no-args constructor is needed when we use @entity annotation. Is it mandatory?

This has to do with how an ORM vendor has made the framework and what requirements he has made for it to work. Specifically for Hibernate yes it is mandatory.

Retrieved from Hibernate Doc

2.2. The entity Java class

  • The no-argument constructor, which is also a JavaBean convention, is a requirement for all persistent classes. Hibernate needs to create objects for you, using Java Reflection. The constructor can be private. However, package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.
  • Related