Careeroza
Entity and Table
Your First Entity
An entity is a Java class whose objects are stored as rows. Mark it with @Entity and give it an @Id:
package in.shopease.entity;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity // this class is persistent
@Table(name = "products") // table name (default would be "product")
public class Product {
@Id // primary key
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name; // -> column "name"
private String description;
private BigDecimal price;
private Integer stock;
private String category;
protected Product() { } // required by JPA
public Product(String name, BigDecimal price, Integer stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public BigDecimal getPrice() { return price; }
public void setPrice(BigDecimal price) { this.price = price; }
public Integer getStock() { return stock; }
public void setStock(Integer stock) { this.stock = stock; }
// other getters/setters ...
}Rules for Entity Classes
- Annotated with
@Entity, with exactly one@Id(or a composite id). - A no-argument constructor,
publicorprotected. Hibernate creates objects with it, then fills the fields. - Not
final, and nofinalpersistent methods — Hibernate creates subclasses (proxies) for lazy loading. - Top-level class (not an inner class).
- Every non-static, non-transient field is persisted by default — you do not need
@Columnon each one.
Note: Java records cannot be entities (they are final and have no no-arg constructor). Records are great for DTOs and, since Hibernate 6.2, for @Embeddable value types.
@Table Options
@Entity(name = "Product") // name used in JPQL queries (default: class name)
@Table(
name = "products",
schema = "shop", // optional database schema
uniqueConstraints = @UniqueConstraint(name = "uk_product_sku", columnNames = "sku"),
indexes = @Index(name = "idx_product_category", columnList = "category")
)
public class Product { ... }Tip: Use plural table names (products, orders). Without @Table, the table for Order would be called order, which is an SQL keyword and breaks queries.