Video in progress

Junior 🌱 Spring

What are the @Entity and @Id annotations for?

@Entity maps a class to a table, and @Id marks the primary key field. Without @Id, JPA can't tell which row an object is.

📖 Answer

@Entity
@Table(name = "products")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, length = 200)
    private String name;

    private BigDecimal price;

    protected Product() {} // no-arg constructor for JPA
}

When you write @Entity, JPA manages this class and maps it to table rows. @Table is needed when the table name is different. @Id is mandatory on every entity. @GeneratedValue says who assigns the id: IDENTITY (database auto-increment), SEQUENCE (PostgreSQL sequence), UUID.

JPA's requirements: a no-arg constructor (at least protected), and the class must not be final (for Hibernate proxies). That's why an entity can't be a record — records are for DTOs.