पाठ 2 / 25

Setting Up JPA with Spring Boot

Configure a datasource, Hibernate and schema migrations in a Spring Boot project.

Dependencies, configuration and schema management

In a Spring Boot application, adding spring-boot-starter-data-jpa and a JDBC driver (for example PostgreSQL) brings in Hibernate, Spring Data JPA, transaction management and the HikariCP connection pool. Configure the datasource URL, user and password in application.yml. The property spring.jpa.hibernate.ddl-auto controls whether Hibernate creates or changes tables: create-drop and update are tempting in tutorials but dangerous in production, because they cannot express data migrations, may drop or miss changes and differ between environments. In real projects, set it to validate (Hibernate checks the mapping matches the schema) or none, and manage the schema with a migration tool such as Flyway or Liquibase: versioned SQL scripts applied in order, reviewed like code. Turn on SQL logging in development to see exactly what Hibernate does. Spring Boot enables open session in view by default (spring.jpa.open-in-view=true) with a warning; disabling it is generally recommended, as discussed later.

application.yml and a Flyway migration

Hibernate validates the schema; Flyway owns it.

spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/shop
    username: shop
    password: ${DB_PASSWORD}
  jpa:
    open-in-view: false
    hibernate:
      ddl-auto: validate            # never create/update in production
    properties:
      hibernate:
        jdbc.batch_size: 50
        order_inserts: true
        order_updates: true
  flyway:
    enabled: true

logging:
  level:
    org.hibernate.SQL: debug                          # SQL statements
    org.hibernate.orm.jdbc.bind: trace                # bound parameter values (Hibernate 6+)

# src/main/resources/db/migration/V1__create_customers.sql
# CREATE SEQUENCE customers_seq START WITH 1 INCREMENT BY 50;
# CREATE TABLE customers (
#   id    BIGINT PRIMARY KEY,
#   name  VARCHAR(100) NOT NULL,
#   email VARCHAR(255) NOT NULL UNIQUE
# );

An architect versus a renovator

ddl-auto=update is a renovator who changes your house without drawings: fine for a tent, risky for a building people live in. Flyway migrations are numbered architectural drawings, reviewed and applied in order.

त्वरित जाँच: What is a safe setting for spring.jpa.hibernate.ddl-auto in production?

  • create-drop
  • update
  • create
  • validate (with Flyway or Liquibase managing the schema)
Answer

validate (with Flyway or Liquibase managing the schema) — validate checks the mapping without changing the schema; migrations are handled by a dedicated tool.