At Generated Value tells JPA, the id is generated. Identity lets the database count up, one, two, three. Sequence uses a separate counter object, in the database. And UUID makes long random ids, which are unique everywhere.
This runner uses a repository, which we'll study next lesson. It creates Dune, and prints its id before saving. Then it saves Dune, and prints the id again. Then it saves Circe, and prints every book. Run it. Before saving, the id is null. After saving, Dune has id one. And Circe got id two.
Loader.javajava
@Componentpublic class Loader implements CommandLineRunner { private final BookRepository books; public Loader(BookRepository books) { this.books = books; } @Override public void run(String... args) { Book dune = new Book("Dune", "Frank Herbert", 9.99); System.out.println("Before save, id = " + dune.getId()); books.save(dune); System.out.println("After save, id = " + dune.getId()); books.save(new Book("Circe", "Madeline Miller", 10.99)); books.findAll().forEach(System.out::println); }}
Output
Before save, id = null
After save, id = 1
Book 1: Dune (9.99)
Book 2: Circe (10.99)
Also uses Book.java
@Entitypublic class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; private double price; protected Book() {} public Book(String title, String author, double price) { this.title = title; this.author = author; this.price = price; } public Long getId() { return id; } public String getTitle() { return title; } public String getAuthor() { return author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Book " + id + ": " + title + " (" + price + ")"; }}
Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {}