Skip to content

Latest commit

 

History

History
112 lines (80 loc) · 2.92 KB

README.md

File metadata and controls

112 lines (80 loc) · 2.92 KB

Spring Boot Postgres Codelab

A minimal Spring Boot REST API that persists User records to a local PostgreSQL database via Spring Data JPA. Built as part of the Ada School "Spring Boot con Postgres" codelab.

Tech stack

  • Java 17
  • Spring Boot 2.7.18 (spring-boot-starter-web, spring-boot-starter-data-jpa)
  • PostgreSQL JDBC driver
  • Maven
  • Hibernate ORM (dialect auto-detected)

Project structure

src/main/java/org/adaschool/datapostgres
├── DataPostgresApplication.java        # application entry point
├── controller/
│   └── UserController.java             # REST endpoints
└── data/
    ├── dto/UserDto.java                # request payload
    ├── entity/User.java                # JPA entity mapped to the "users" table
    ├── exception/UserNotFoundException.java
    └── repository/UserRepository.java  # Spring Data JPA repository

Prerequisites

  • JDK 17+
  • Maven 3.6+
  • A running local PostgreSQL server (any version) with a user/password and an existing database created for this project

Database setup

Create a role and database (adjust names/password as you like):

CREATE ROLE codelab_user LOGIN PASSWORD 'codelab123';
CREATE DATABASE codelab OWNER codelab_user;

Configuration

Connection settings live in src/main/resources/application.properties:

spring.datasource.url=jdbc:postgresql://localhost:5432/codelab
spring.datasource.username=codelab_user
spring.datasource.password=codelab123
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Update url, username, and password to match your own local PostgreSQL setup. spring.jpa.hibernate.ddl-auto=update lets Hibernate create/update the users table automatically on startup, and data persists across restarts.

Running the application

mvn spring-boot:run

The API starts on http://localhost:8080 (override with --server.port=<port> if 8080 is taken). On first boot, Hibernate creates the users table in the configured database.

API

Create a user

POST /v1/user
Content-Type: application/json

{
  "name": "Ada Lovelace",
  "email": "ada@example.com"
}

Response 200 OK

{
  "id": 1,
  "name": "Ada Lovelace",
  "email": "ada@example.com"
}

Get a user by id

GET /v1/user/{id}

Response 200 OK — same shape as above.

Response 404 Not Found if no user exists with that id.

Verifying persistence

  1. Start the app and create a user via POST /v1/user.
  2. Stop the app (Ctrl+C).
  3. Start it again with mvn spring-boot:run.
  4. GET /v1/user/{id} for the user created in step 1 — it should still be returned, confirming the data survived the restart in PostgreSQL.

Build

mvn clean package

Produces an executable jar at target/data-postgres-0.0.1-SNAPSHOT.jar, runnable with java -jar target/data-postgres-0.0.1-SNAPSHOT.jar.