JPA providers, such as Hibernate (or Eclipse Link) rely on reflection to instantiate entity objects during database operations. Hibernate uses the Reflection API to create instance of Entity beans, usually when you call get()
or load()
methods. The method Class.newInstance()
is used for this and it requires no-args constructor.
An empty constructor allows these providers to create instances of your entity class without providing any constructor arguments.
Let's consider an example entity class:
@Entity
public class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Empty constructor for JPA
public MyEntity() {
// Default constructor
// Sonarqube recommends to add a descriptive comment here as a good practice
}
// Constructors, getters, setters, and other methods...
}
So if you don't have no-args constructor in entity beans, hibernate will fail to instantiate it, and you will get HibernateException
.
Reflection is powerful, but it's important to be cautious when employing it. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it.
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
More resources
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium