At Entity tells JPA, save books in a table. At Id marks the primary key, the unique id of each row. The other fields become columns. JPA needs an empty constructor, which can be protected. And our own constructor makes new books, without an id.
Book.javajava
@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; } // getters, setPrice and toString follow}
An entity must be a class, not a record, because JPA fills its fields. It needs an at Id field. It needs a constructor with no arguments. And it usually has getters, so Jackson can turn it into JSON.
Show SQL equals true, prints every SQL statement that Hibernate runs. With H2, Hibernate creates the tables for us, at startup. Run it. Hibernate created a table called book. It has an id column, generated by identity, and one column for each field.
application.propertiesini
spring.jpa.show-sql=true
Output
Hibernate: create table book (price float(53) not null, id bigint generated by default
as identity, author varchar(255), title varchar(255), primary key (id))
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> {}
At Table changes the table name. At Column can make a column required, or set its length. It can also rename the column. And at Transient means, don't save this field at all.