This project demonstrates three approaches to work with PostgreSQL schemas in Spring Boot:
- Default schema for all entities via
hibernate.default_schema - Per-entity schema using
@Table(schema = "...") - Database search path using JDBC param
currentSchema=my_schema
Tech:
- Java 21
- Spring Boot 3.3.x
- Spring Data JPA
- PostgreSQL 16
- Gradle (Groovy)
- Docker & Docker Compose
Requires Docker installed.
docker compose up --buildThis will:
- Start Postgres on port
5432 - Build & run the Spring Boot app on port
8080
Once it's up, try these endpoints:
-
POST http://localhost:8080/users/default/{name}
Inserts intomy_schema.users_default(default schema) -
POST http://localhost:8080/users/custom/{email}
Inserts intoother_schema.users_custom(entity-level schema) -
POST http://localhost:8080/users/mixed/{phone}
Inserts intomy_schema.users_mixed(resolved viacurrentSchema/ search_path) -
GET http://localhost:8080/users/all
Returns counts for all three tables
Stop all containers:
docker compose downData persists in the named Docker volume
pgdata(remove viadocker volume rm pgdata).
If you want to run locally (without Docker), adjust spring.datasource.* in src/main/resources/application.yml
to point to your local PostgreSQL, then:
./gradlew bootRunschema.sqlcreates two schemas:my_schemaandother_schema.application.ymlsets:hibernate.default_schema=my_schema(Approach A)- JDBC URL includes
?currentSchema=my_schemaso search path prefersmy_schema(Approach C)
@Table(schema="other_schema")onUserCustomshows Approach B for one entity.
You can mix-and-match these depending on your needs.