Configuring Hibernate and JPA
Configuring Hibernate and JPA
Hibernate needs a database connection, a dialect, and rules for schema handling before it can persist anything. In a plain JPA environment you configure it in persistence.xml, while Spring Boot drives it entirely from application.properties and conventions.
The datasource comes first
Every persistence setup begins with connection details. Provide the URL, username, and password. In a Boot app, the datasource dependency and the JPA starter trigger auto-configuration; swap H2 for PostgreSQL by changing the URL and the driver dependency.
spring.datasource.url=jdbc:postgresql://localhost:5432/app
spring.datasource.username=app
spring.datasource.password=secret
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Dialect and driver
The driver speaks the database's wire protocol; Hibernate infers the dialect from the driver and database metadata in modern versions, so you rarely set it explicitly. If you ever see SQL that does not match your database, that is when a dialect setting is needed.
DDL strategy
ddl-auto controls schema generation: update is convenient in development but unsafe in production, validate checks that tables match your entities, and none leaves schema to you. Prefer migrations (Flyway or Liquibase) for production schema evolution.
Naming and strategy
Physical naming maps Java field names to column names, and you can add your own naming strategy to enforce a company convention, such as snake_case columns. Keep the mapping explicit with @Table and @Column where clarity matters.
Key Points
- Configuration starts with a datasource and the JPA starter.
- Hibernate detects the dialect from your driver and database.
ddl-auto=updateis for development; use migrations in production.- Physical naming strategies enforce consistent column names.
- Enable
show-sqlwhile learning to inspect generated SQL.