Search code examples
javajpaconstructoreclipselink

JPA: is the default constructor required to be empty?


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.


Solution

  • 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.