Table of Contents
In this post, we are going to explore the reasons why does Hibernate need a no-arg constructor. The no-arg constructor need to be protected or public.
A primer on the no-arg constructor
When you declare a class without any constructor, the compiler create a default no-arg constructor for you. However, when you define constructor(s) with arguments, this is no longer the case. Thus, when working with Hibernate, when you have constructors with argument, you need to explicitly declare a no-arg constructor.
Why does Hibernate Need A No-arg constructor
Hibernate requires that entities have a no-args constructor (a constructor without any parameters) due to various aspects of its internal operations and its reliance on the Java reflection API. Let’s delve into these reasons in more detail.
During the process of retrieving data from the database and transforming it into Java objects, Hibernate has to create instances of entities. To accomplish this, Hibernate first uses the no-args constructor to instantiate the entity object, after which it proceeds to populate the object’s properties with the corresponding data from the database.
Lazy loading and proxies
Hibernate employs proxy objects to achieve lazy loading, a strategy in which associated entities are fetched from the database solely upon explicit request. Proxies are derived classes of the real entities and must be instantiated via the parameter-less constructor. Hibernate generates proxy instances to intercept property access of the entity and initiate the lazy loading feature.
Hibernate heavily depends on the utilization of the Java reflection API for interacting with entities and their attributes. When employing methods such as Class.newInstance() (which is deprecated as of Java 9) or other reflection-driven mechanisms, it becomes necessary to have a no-argument constructor in order to generate instances of the entity class.
Hibernate provides the functionality to retrieve specific attributes of an entity or even aggregated values through queries. In order to achieve this, Hibernate may require the ability to dynamically instantiate entities, which is made possible by having a default constructor.
Once an entity instance is created, Hibernate automatically assigns values to its properties using the data retrieved from the database. By including a no-args constructor, the entity object is initialized with default values, ensuring that Hibernate can then populate it with the actual data.
Now you know the reason why Hibernate requires a no-arg constructor for entities.
I build softwares that solve problems. I also love writing/documenting things I learn/want to learn.