Is it necessary that the default contructor is empty when working with JPA? Since I have no clue of how JPA internally works I somehow fear that an object could be falsely initialised by JPA when the default contructor does some stuff on his own like filling attributes with default values and the like.
Thanks.
Default or No-Arg Constructor. The JPA specification requires that all persistent classes have a no-arg constructor. This constructor may be public or protected.
An empty constructor is required when we need to create a new instance via reflection by our framework. If we don't create any other constructor with arguments for the class, we don't need to create an empty constructor because one default will already be present.
Because it often happens that the JPA provider has to instantiate your domain object dynamically. It cannot do so, unless there is a no-arg constructor - it can't guess what the arguments should be.
It's not mandatory to define default constructor, but if you are writing Hibernate persistent class, JPA entities, or using the Spring framework to manage object creation and wiring dependencies, you need to be a bit careful.
To minimize runtime overhead by JPA, but enforce constraints when creating new instances in user code:
The short answer is no. It is not required to be empty.
However, you need to be aware that when the JPA implementation materializes an instance from persistence, it will do things to the instance after the no-args constructor completes. This might undo things that your constructor has done.
To understand whether the constructor needs to be empty, you need to consider that the constructor is going to be called in two scenarios.
When you are creating a "new" object, the constructor needs to produce an object that is sufficiently initialized to be used by normal code. Fields that need to be initialized to non-default states should be dealt with.
When JPA is materializing an object from the persistent store, the materialization is then going to "fill in the details" of the newly constructed instance. This will typically overwrite the object state of the constructed object.
Of course, your code may be designed so that it doesn't directly use the no-args constructor. This renders the first scenario moot, and also renders moot the potentially wasteful "double initialization" that might occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With