9.2 Entity Mapping and Strategies
The first step in using JPA is making declarations about which Table in the database a given Java Class corresponds to. A mapped class is termed an Entity.
Basic Mapping Annotations
To map an entity, the most essential annotations are @Entity and @Id.
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.AccessLevel;
@Entity
@Table(name = "users") // Used to explicitly define plural or specific table names
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED) // A default constructor is required for JPA.
public class User {
@Id // Indicates that this field is the Primary Key (PK) of the table
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// The CamelCase 'userEmail' automatically maps to a snake_case 'user_email' column.
@Column(nullable = false, length = 100, unique = true)
private String userEmail;
@Column(nullable = false)
private String password;
@Column(length = 50)
private String nickname;
// Convenience method for business logic (e.g. changing nickname)
public void changeNickname(String newNickname) {
this.nickname = newNickname;
}
}
@Entity: Indicates to JPA that this class is a managed entity.@Id: Marks the field as the primary key (PK).@Column: Maps an object's field to a table column. You can set constraints (nullable,unique,length) for the DB schema here. (Even if omitted, JPA recognizes fields as columns automatically.)
Primary Key Generation Strategies (@GeneratedValue)
Different databases adopt different methods to auto-generate identifiers. To mitigate this disparity, varied strategy values are offered:
GenerationType.IDENTITY(Highly Recommended): Delegates ID generation to the database. Equivalent toAUTO_INCREMENTin MySQL. You can comprehend the ID's value only post-save.GenerationType.SEQUENCE: Creates keys using a Sequence object in the database. Predominantly used in Oracle or PostgreSQL.GenerationType.UUID(Modern JPA option): Automatically computes a 32-character UUID string, optimal for distributed systems or where unpredictable keys are prioritized. (The ID type must be aUUIDorString.)
By wrapping up your entity design and launching the application with the ddl-auto: update option in application.yml, you'll notice JPA analyzes your entity structure and automatically executes CREATE statements to construct tables inside the database.