Spring Boot Spring Data JPA
Spring Data JPA connects your Java objects to a relational database. You define entity classes and Spring Data generates all the SQL — you never write INSERT INTO or SELECT * FROM for basic operations.
What JPA Is
JPA (Java Persistence API) is a specification that maps Java objects to database tables. Hibernate is the most popular JPA implementation and is included automatically when you add the Spring Data JPA starter.
┌─────────────┐ ┌─────────────┐ ┌──────────────┐ │ Java Class │ JPA │ Hibernate │ JDBC │ Database │ │ (Entity) │────────▶│ (maps it) │─────────▶│ Table │ └─────────────┘ └─────────────┘ └──────────────┘ User.java generates SQL users table
Adding the Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Also add your database driver, e.g., MySQL -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
Creating an Entity
An entity is a Java class that maps to a database table. Annotate it with @Entity:
@Entity
@Table(name = "users") ← Maps to the "users" table
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) ← Auto-increment ID
private Long id;
@Column(nullable = false) ← Column cannot be null
private String name;
@Column(unique = true) ← Each email must be unique
private String email;
private int age;
// Getters and setters
}
Entity → Table Mapping Diagram
Java Entity: User Database Table: users ───────────────────────────────── ───────────────────────────────── @Id Long id → id BIGINT PRIMARY KEY AUTO_INCREMENT @Column String name → name VARCHAR(255) NOT NULL @Column(unique=true) String email → email VARCHAR(255) UNIQUE int age → age INT
Common JPA Annotations
Annotation What It Does ────────────────────────── ───────────────────────────────────────── @Entity Marks the class as a database entity @Table(name="...") Sets the table name @Id Marks the primary key field @GeneratedValue Auto-generates the ID value @Column(nullable=false) Adds NOT NULL constraint @Column(unique=true) Adds UNIQUE constraint @Transient Field is NOT saved to the database @OneToMany / @ManyToOne Defines relationships between tables
Defining Relationships
One-to-Many: One User has Many Orders
User (one)
│
┌────────────┼────────────┐
▼ ▼ ▼
Order #1 Order #2 Order #3 (many)
@Entity
public class User {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Order> orders;
}
@Entity
public class Order {
@ManyToOne
@JoinColumn(name = "user_id") ← Foreign key column in orders table
private User user;
}
Configuring the Database Connection
# application.properties spring.datasource.url=jdbc:mysql://localhost:3306/estudy_db spring.datasource.username=root spring.datasource.password=secret spring.jpa.hibernate.ddl-auto=update # auto-create or update tables spring.jpa.show-sql=true # print SQL to console during dev
ddl-auto Options
Value Behavior ─────────── ────────────────────────────────────────────── create Drop and recreate tables every startup create-drop Create on start, drop on shutdown update Update tables to match entities (add columns) validate Check tables match entities — error if not none Do nothing (use for production)
Summary
- JPA maps Java classes (entities) to database tables automatically
- Hibernate is the JPA implementation included with Spring Data JPA
@Entity,@Id, and@Columnare the core annotations for mapping@OneToManyand@ManyToOnedefine relationships between tables- Set
ddl-auto=updatefor development andnonefor production
