Mapping a Table with @Entity
An @Entity is a Java class that maps to a database table — each object becomes a row, no SQL needed.
What you will learn
- Mark a class as an @Entity
- Define the id with @Id
- Understand the class-to-table idea
Objects in, rows out
So far your data vanished when the app stopped. To store it permanently you use a database. JPA (Java Persistence API — Java’s standard way to save objects to a database) lets you work with the database using plain Java objects instead of SQL (Structured Query Language — the text commands databases normally use, like SELECT and INSERT). A class becomes a table; an object becomes a row.
The first step is to mark a class as an entity — a class JPA will save to a table.
Add the starters
On Initializr (or in pom.xml) add Spring Data JPA and a database. For learning, the H2 in-memory database (one that lives in the computer’s memory while the app runs, so it needs no install — but it is wiped each time the app restarts) needs zero setup:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>Note: Output: (No output — these add JPA and a ready-to-use in-memory database, so you need no separate database install while learning.)
Mark the class as an entity
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; // the database fills this in
private String name;
private double price;
protected Product() { } // JPA needs a no-argument constructor
public Product(String name, double price) {
this.name = name; this.price = price;
}
// getters and setters ...
}Note: Output:
When the app starts, Spring creates a table roughly like:
CREATE TABLE product (id BIGINT PRIMARY KEY, name VARCHAR, price DOUBLE);
You wrote a Java class; JPA built the matching table. @GeneratedValue means the database assigns each new id automatically.
| Annotation | Job |
|---|---|
@Entity | This class maps to a database table |
@Id | This field is the primary key (unique id) |
@GeneratedValue | The database generates the id for you |
Tip: Compare this to writing CREATE TABLE and INSERT SQL by hand. With JPA your class is the table definition, and saving an object inserts a row. Less code, fewer mistakes.
Watch out: JPA needs a no-argument constructor (it builds objects when reading rows). It can be protected, but it must exist — leaving it out causes a startup error.
Q. What does the @Entity annotation tell JPA?
✍️ Practice
- Create a
Bookentity with an auto-generated id, title and author. - List which three annotations make a class a JPA entity and what each does.
🏠 Homework
- Create a
Studententity (id, name, course, age) ready to be saved to a table.