🎓 A1Learner
🔍
0 of 50 lessons completed

A First Entity

An entity is a Java class that JPA maps to a database table. The class holds the fields, and the table holds the rows.

Mark the class and its id

The class carries @Entity. The id carries @Id and @GeneratedValue.

@Entity
public class Task {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
}

Add the other fields

The title holds text. The done flag holds true or false.

private String title;
private boolean done;

Example

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Task {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private boolean done;

    public Task() {
    }

    public Task(String title, boolean done) {
        this.title = title;
        this.done = done;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isDone() {
        return done;
    }

    public void setDone(boolean done) {
        this.done = done;
    }

    public static void main(String[] args) {
        Task task = new Task("Buy milk", false);
        System.out.println(task.getTitle() + " " + task.isDone());
    }
}

Key points

  • @Entity marks a class as an entity.
  • @Id marks the field that names each row.
  • The id is the number that tells one row from another.
  • @GeneratedValue tells JPA to make the id itself.
  • An entity needs a constructor with no arguments.
  • The fields hold the data, and the table holds one column per field.

In this example, @Entity marks Task as an entity. The id field carries @Id and @GeneratedValue. The title and done fields hold the task data. The first constructor takes no arguments. The second constructor sets the title and the done flag. The getters read the fields. The setters change the fields. The main method makes a task and prints its title and done flag.

Note

The id starts empty, and JPA fills it when the row is saved.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does @Entity mark?