From the course: Java Persistence with JPA and Hibernate

Unlock the full course today

Join today to access over 24,400 courses taught by industry experts.

Specifying the primary key

Specifying the primary key

- [Instructor] An entity should have a primary key. Let's look at how to specify that. There's an ID field in the book class. This is mapped to the book_id column in the book table of the database. In fact, having this ID field is mandatory for an entity class, even if your table doesn't have a primary key, which sometimes is the case in the real world, there must be an ID in the entity class. But of course in this case, there's a primary key in the book table. So let's go to the database and to the book table. So the primary key is book_id. If there are no columns in the table that can act as a primary key, in most cases, there's an artificial primary key like ID in the table that is set to auto increment. Usually this ID field in the class is what will be mapped to the primary key of the table. So how can we specify that the ID field in the class is actually a primary key? Once again, annotations to the rescue. The @Id annotation is used to indicate that a field is the primary key…

Contents