Your First JPA Entity
Your First JPA Entity
An entity is a class mapped to a table, and everything in JPA happens on entities. Writing one correctly requires three things: the mapping annotations, a primary key strategy, and a no-argument constructor so the framework can materialize instances.
Annotation basics
@Entity registers the class; @Table optionally names the table. Fields map to columns automatically, and @Id marks the primary key. JPA fields can be private - Hibernate uses reflection to populate them.
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
protected Product() {}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
// getters and setters
}
The no-argument constructor
JPA needs to construct instances when it reads rows, so the framework requires a no-arg constructor. Make it protected rather than public to keep the API tight, and keep a full constructor for application code.
Entity lifecycle
Entities move through states: new (not persisted), managed (attached to a session), detached, and removed. A managed entity's changes are flushed to the database at commit. Understanding the lifecycle prevents surprises, like detached entities not auto-saving.
Value objects inside entities
JPA supports embedded value objects with @Embeddable. Use them for grouped fields such as an address with street, city, and postal code, so the entity stays expressive and the mapping stays explicit.
Key Points
@Entityplus@Idis the minimum mapping.- Always provide a no-arg constructor for the framework.
- Entities move between managed, detached, and removed lifecycle states.
- Only managed entities flush changes automatically.
- Use
@Embeddablefor grouped value fields.