Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 22

JPA Entities: Defining with `@Entity`, `@Id`, and Schema Generation

This lesson is built with resources from youtube.com, baeldung.com and 1 more site.

Hello! In our last session, we successfully connected our Spring Boot application to a live PostgreSQL database running in Docker. We now have a solid foundation for data persistence. However, our database is currently empty.

Today's lesson is about bringing our application's data model to life within that database. We'll define our first JPA Entity, which is the Spring ecosystem's way of describing a database table using a Java class. You'll learn how to map a class to a table, define a primary key, and configure Spring to automatically generate the database schema for you. This process is known as Object-Relational Mapping (ORM).

By the end of this lesson, you will have a User table created in your PostgreSQL database, generated entirely from your Java code, fulfilling the learning outcome: "Define a JPA entity with @Entity and @Id, and configure automatic schema generation."

1. From Mongoose Schemas to JPA Entities

In your experience with the MERN stack, you've used Mongoose schemas to define the structure of documents within a MongoDB collection.

// Mongoose Schema (Node.js/Express)
const userSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true }
});
const User = mongoose.model('User', userSchema);

The Java Persistence API (JPA) accomplishes the same goal for relational databases but uses annotations on a standard Java class (a POJO - Plain Old Java Object). The concept is identical: you define your data model in your application code, and the underlying framework (in our case, Hibernate, the default JPA implementation in Spring) translates it into database structures and queries.

Let's begin building our User entity. Here is a simplified Entity-Relationship Diagram (ERD) for our blog platform. Today, we'll focus on creating the user table.

Blog Platform Database Schema ERD
This diagram shows the target schema for our blog. We'll start by defining the `user` entity, which will eventually be linked to `post` entities.

2. Defining Your First Entity

An entity is a Java class that represents a table in a relational database. To mark a class as an entity, we use the @Entity annotation. Every entity must also have a primary key, which we define using the @Id annotation.

Automatically Create a Database Schema With Spring Boot

This article from Baeldung provides a clear walkthrough of the essential annotations and configuration for schema generation. It will serve as our primary guide for this section.

Read section 2.4, 'Creating Entity Classes'. This short section introduces the @Entity, @Id, and @GeneratedValue annotations, which are the fundamental building blocks of a JPA entity.

Now, let's apply this to our project.

Hands-On: Create the User Class

  1. In your project's main package (e.g., com.example.blogplatform), create a new subpackage named domain. This is a common convention for holding your core business model objects (entities).
  2. Inside the domain package, create a new Java class named User.

Add the following code to your User.java file. We'll start with just the basic fields and the required annotations.

package com.example.blogplatform.domain;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "users") // Optional: specifies the table name. If omitted, it defaults to the class name "user".
public class User {

    @Id
    private Long id;

    private String firstName;
    private String lastName;
    private String email;
    private String password;

    // We will add getters, setters, and constructors later.
    // For now, JPA can work with fields directly via reflection.
}

At this point, we've told JPA that this class maps to a users table and has a primary key field named id. But we haven't told it how the id value should be generated.


3. Primary Key Generation Strategies

In MongoDB, the _id is automatically handled for you. In the SQL world, we have several strategies for generating primary keys, and we must be explicit. This is where the @GeneratedValue annotation comes in.

This concise diagram illustrates the key annotations involved in generating primary keys.

JPA Primary Key Generation Annotations
This diagram shows how `@Id` works with `@GeneratedValue` and `@SequenceGenerator` to control primary key creation.

The most common strategies for @GeneratedValue are:

  • GenerationType.IDENTITY: Relies on an auto-incrementing column in the database. When you insert a row, the database assigns the next available ID. This is simple and efficient. In PostgreSQL, this corresponds to a SERIAL or BIGSERIAL column type.
  • GenerationType.SEQUENCE: Uses a dedicated database object called a sequence to fetch the next ID before inserting a row. This is highly performant, especially for batch inserts, and is the preferred strategy for many large-scale applications.
  • GenerationType.AUTO: Lets the JPA provider (Hibernate) choose the best strategy for the connected database. For PostgreSQL, it will default to SEQUENCE.
  • GenerationType.TABLE: Simulates a sequence using a separate table. It has significant performance overhead and is rarely used today.

To understand these strategies in action, the following video provides an excellent demonstration.

Spring Data JPA Tutorial - #9 - Primary key generation strategies AUTO, IDENTITY, SEQUENCE and TABLE

This video from Java Guides clearly explains and demonstrates the four primary key generation strategies supported by JPA.

Watch the sections on GenerationType.IDENTITY (04:47 - 07:36) and GenerationType.SEQUENCE (07:36 - 13:13). Pay attention to: How each strategy is configured using annotations. The resulting SQL CREATE TABLE statement that Hibernate generates. The conceptual difference: IDENTITY relies on the column's own properties, while SEQUENCE uses a separate database object.

For our project, IDENTITY is a perfectly suitable and straightforward choice. Let's update our User entity.

Hands-On: Add @GeneratedValue

Modify your User.java file to include @GeneratedValue.

package com.example.blogplatform.domain;

import jakarta.persistence.*; // Make sure to import everything from this package

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    // ... other fields remain the same
    private String firstName;
    private String lastName;
    private String email;
    private String password;
}

4. Configuring Automatic Schema Generation

We've defined what the table should look like, but we haven't told Spring Boot when or how to create it. This is controlled by a single, powerful property in application.yml.

Automatically Create a Database Schema With Spring Boot

Let's return to the Baeldung article to understand how to control schema generation.

Read section 2.3, 'Understanding spring.jpa.hibernate.ddl-auto Options'. This is a critical concept. Understand the behavior of create, update, validate, and none.

For local development, update is very convenient. It instructs Hibernate to compare your entities with the database schema on startup and apply any necessary changes (like adding new tables or columns).

Important Note: Using ddl-auto with update or create in production is highly discouraged. Production database changes should always be managed through a dedicated migration tool like Flyway or Liquibase to ensure control, versioning, and safety. We'll cover this later in the course.

Hands-On: Update application.yml

Open your src/main/resources/application.yml file and add the jpa properties.

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/blog_platform_db
    username: admin
    password: password
    driver-class-name: org.postgresql.Driver
  jpa:
    hibernate:
      ddl-auto: update # Tells Hibernate to update the schema on startup
    show-sql: true # Prints the generated SQL statements to the console
    properties:
      hibernate:
        format_sql: true # Formats the printed SQL for better readability

The show-sql property is incredibly useful for debugging. It lets you see the exact SQL statements Hibernate is executing, demystifying the "magic" of the ORM.


5. Runtime Observation and Debugging

Now, let's see our work in action.

  1. Make sure your PostgreSQL container is running (docker compose up -d).
  2. Start your Spring Boot application from your IDE.

Observe the console output. Thanks to show-sql: true, you should see a log entry with a CREATE TABLE statement similar to this:

Hibernate: 
    create table users (
        id bigserial not null,
        email varchar(255),
        first_name varchar(255),
        last_name varchar(255),
        password varchar(255),
        primary key (id)
    )

Notice a few things:

  • Hibernate automatically translated the class name User to the table name users (as we specified with @Table).
  • It converted the camelCase field names (firstName) to snake_case column names (first_name). This is a default convention called a "physical naming strategy".
  • The id column is of type bigserial, which is PostgreSQL's auto-incrementing 64-bit integer type, exactly what GenerationType.IDENTITY maps to.

To confirm, use your IDE's database client or a tool like DBeaver to connect to your blog_platform_db database. You will now see the users table with the correct columns.

Debugging Task: The "No identifier" Error

This is one of the most common errors when starting with JPA. Let's reproduce it to understand it.

  1. Stop your application.
  2. In User.java, comment out the @Id annotation.
    // @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
  3. Try to start the application again.

It will fail to start with a long stack trace. Scroll through the error message, and you will find the root cause:

org.hibernate.AnnotationException: No identifier specified for entity: com.example.blogplatform.domain.User

This error is Hibernate telling you exactly what's wrong: "You told me this class is an @Entity, but you didn't tell me which field is the @Id." Uncommenting the @Id annotation will fix this.


Conclusion

Excellent work! You have successfully defined a JPA entity and configured Hibernate to automatically generate the corresponding database table. This is a fundamental skill for any Spring developer.

Key Takeaways:

  • @Entity marks a Java class as a database entity.
  • @Id is mandatory and designates the primary key field.
  • @GeneratedValue specifies the strategy for generating primary key values, with IDENTITY and SEQUENCE being the most common.
  • The spring.jpa.hibernate.ddl-auto property controls automatic schema management. We use update for development convenience.
  • show-sql: true is your best friend for debugging and understanding what the ORM is doing behind the scenes.

Preview of the Next Lesson:

We have a users table, but our application has no way to perform operations like INSERT, SELECT, or UPDATE on it. In the next lesson, we will implement a Spring Data JPA Repository. This is an interface that, with almost no code, will give us a full set of CRUD methods for our User entity, much like a Mongoose model provides methods like .find() and .save().