Video in progress
What requirements must a class meet to be an @Entity?
The class needs @Entity, an @Id, and a public or protected no-arg constructor. It should not be final, and its persistent fields and methods should not be final either, otherwise Hibernate can't create a proxy.
📖 Answer
A minimal correct entity:
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
protected Product() { } // for Hibernate
public Product(String name) { this.name = name; }
}
Why these rules exist:
- no-arg constructor: when Hibernate reads from the database, it creates the object through reflection and then fills in the fields;
- not
final: for lazy loading Hibernate generates a proxy that subclasses your class, and you can't subclass afinalclass; @Id: identifies each entity inside the persistence context.
A Java record can't be an entity: it is final and its fields are immutable. Records are great for DTO projections, though.
In Kotlin this comes up a lot because classes are final by default, which is why the kotlin-jpa and all-open plugins are used.
Sign up to mark studied questions and save your progress.