Why we make Entity Class final?
In Hibernate, an entity class represents a table in a database, and instances of this class represent rows in that table. Making an entity class final can cause issues for the following reasons:
1. Â Proxying
Hibernate uses proxies for lazy loading of entities. A proxy is a subclass that Hibernate generates at runtime to represent the entity. If the entity class is final, Hibernate cannot create a proxy subclass, and lazy loading will not work.
2. Â Inheritance Mapping
Hibernate supports inheritance mapping strategies. If an entity class is final, it cannot be extended, and inheritance mapping becomes impossible.
3. Â Enhancements and Instrumentation
Hibernate may need to enhance or instrument entity classes for various purposes, such as bytecode manipulation. A final class restricts these enhancements.
Table of Contents
Java Example
Incorrect Example: Final Entity Class
java
@Entity
public final class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
// Getters and Setters
}
In the above example, if we try to use lazy loading or any other feature that requires proxying, Hibernate will throw an exception because it cannot create a proxy for a final class.
Correct Example: Non-Final Entity Class
java
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
// Getters and Setters
}
In this correct example, the Employee class is not final, allowing Hibernate to create proxies for lazy loading and to use inheritance mapping if needed