DEV Community

Cover image for From Zero to CRUD - A Tiny Spring Boot H2 Boilerplate You’ll Actually Use
boiler_agents
boiler_agents

Posted on

From Zero to CRUD - A Tiny Spring Boot H2 Boilerplate You’ll Actually Use

TL;DR: A friendly Spring Boot starter that gives you a working Book CRUD API with H2, DTOs, a service layer, and global error handling — clone, run, and start experimenting in under a minute.


Introduction

When I first started with backend work, I wasted entire afternoons wiring up a database just to test one endpoint. That’s boring and unnecessary. This boilerplate flips that script: it’s a tiny, realistic skeleton that removes the friction so you can focus on the idea you actually care about.

This repo solves the problem of wasted setup time by providing a minimal, well-structured example you can safely modify, extend, and copy into real projects.
Ideal for: students, bootcamp grads, freelance devs, and anyone who wants a quick, clean prototype.


Why this boilerplate?

  • Saves time: Clone, run, and get a full CRUD API in ~60 seconds. No database install, no painful config.
  • Realistic but minimal: Structure mirrors production apps (DTOs, service layer, repository, global exception handler) so learning transfers to real projects.
  • Opinionated best pactices: Enforces separation of concerns (controller → service → repo), consistent error shapes, and DTO usage so your API stays maintainable as it grows.
  • Includes: H2 in-memory DB with data.sql sample data, a Postman collection, and basic tests to get you started.

Features

  • Minimal Spring Boot 3 CRUD API for a Book resource — id, title, author.
  • H2 in-memory database for zero-config local testing (with H2 console).
  • DTO-based requests/responses to keep controllers tidy and versionable.
  • Service layer that isolates business logic for easier testing.
  • Global exception handling with a custom ResourceNotFoundException for consistent client errors.
  • Sample data loaded at startup via data.sql.

Roadmap (short & actionable):

  • Add Swagger/OpenAPI for interactive docs.
  • JWT auth example + role-based access control.
  • Postgres + Flyway migrations for persistence.
  • Pagination, sorting, and filtering on list endpoints.

Quick, human setup

I prefer simple instructions you can actually follow.

Local setup (the five-minute version)

  1. Clone:
git clone https://github.com/boileragents/springboot-h2-crud-demo
cd springboot-h2-crud-demo
Enter fullscreen mode Exit fullscreen mode
  1. Open in your IDE (IntelliJ, VS Code, or Eclipse).
  2. Run:
mvn spring-boot:run
Enter fullscreen mode Exit fullscreen mode
  1. Visit http://localhost:8080 — your API is live.
  2. Play with the H2 console at http://localhost:8080/h2-console (JDBC: jdbc:h2:mem:testdb, user: sa, blank password).

To build and run the jar:

mvn clean package
java -jar target/springboot-h2-crud-demo-0.0.1-SNAPSHOT.jar
Enter fullscreen mode Exit fullscreen mode

Usage & Examples

API endpoints (friendly names)

Method Endpoint Friendly name
POST /books Create Book
GET /books List Books
GET /books/{id} Get Book by ID
PUT /books/{id} Update Book
DELETE /books/{id} Delete Book

Try it: fetch all books

GET http://localhost:8080/books
Enter fullscreen mode Exit fullscreen mode

Sample response:

[
  { "id": 1, "title": "Spring Boot Basics", "author": "John Doe" },
  { "id": 2, "title": "A Practical Guide", "author": "Jane Smith" }
]
Enter fullscreen mode Exit fullscreen mode

Create a book (cURL)

curl -X POST "http://localhost:8080/books" \
  -H "Content-Type: application/json" \
  -d '{"title":"Spring Boot Basics","author":"John Doe"}'
Enter fullscreen mode Exit fullscreen mode

Sample response:

{ "id": 3, "title": "Spring Boot Basics", "author": "John Doe" }
Enter fullscreen mode Exit fullscreen mode

Configuration

Key files and settings:

  • application.properties — server port, H2 console, and datasource defaults.
  • data.sql — initial seed data loaded at startup.
  • Switch to a production DB by updating the datasource properties and adding migrations (Flyway / Liquibase).

Project Structure (real and small)

.
├── src/
│   ├── main/java/com/demo
│   │   ├── controller/        # BookController.java
│   │   ├── dto/               # BookDTO.java
│   │   ├── entity/            # Book.java
│   │   ├── service/           # BookService.java
│   │   ├── repository/        # BookRepository.java
│   │   └── exception/         # GlobalExceptionHandler.java, ResourceNotFoundException.java
│   └── main/resources/
│       ├── application.properties
│       └── data.sql
├── springboot-h2-crud-demo.postman_collection.json     #Postman Collection for testing
├── pom.xml
└── README.md
Enter fullscreen mode Exit fullscreen mode

Small, obvious, and easy to extend.


Tiny, practical lessons (real advice)

  • DTOs early: They make versioning and response shaping painless.
  • Keep controllers thin: Controllers should orchestrate, not implement business rules. Put logic in services.
  • Global error format: One error shape for all endpoints makes front-end devs very happy.
  • Test the service layer: Unit tests for business logic are fast and stable; integration tests can cover persistence.

And remember: this repo endorses opinionated best pactices—apply them so your next prototype doesn’t become a maintenance headache.


Testing

  • Run unit tests:
mvn test
Enter fullscreen mode Exit fullscreen mode
  • Add integration tests with Testcontainers if you want DB-backed CI runs.

Deployment & CI ideas

  • Build and publish a Docker image:
docker build -t boileragents/springboot-h2-crud-demo:latest .
Enter fullscreen mode Exit fullscreen mode
  • CI flow (recommended): Build → Test → Publish image → Deploy to staging → Promote to production.
  • Want a GitHub Actions snippet? I can add a simple workflow for build/test/publish.

Extending & Customization

  • Add endpoints: New controller + DTO + service + repo. Keep tests in sync.
  • Swap DB: Change datasource props and add migrations (Flyway recommended).
  • Add auth: Plug in Spring Security + JWT; protect controllers with annotations.

Troubleshooting / FAQ

  • App doesn't start? Check Java version (17+), port conflicts, and logs for missing beans.
  • H2 console unreachable? Ensure spring.h2.console.enabled=true and correct JDBC URL.
  • Need persistence across restarts? Use file-based H2 or a persistent DB (Postgres/MySQL).

Contributing

Pull requests, bug reports, and small improvements are welcome.

  1. Fork the repo
  2. Create a branch: git checkout -b feat/my-change
  3. Run tests and linters locally
  4. Open a PR with a clear description

Please follow CONTRIBUTING.md and CODE_OF_CONDUCT when available.


License

MIT — see LICENSE for details.


About Boileragents

Boileragents builds focused starters so you can skip setup and start building.
GitHub: https://github.com/boileragents • Email: boileragents@gmail.com


Links & Resources


If this saved you time, please ⭐ the repo and leave a short note about what you'd like next — Swagger, auth examples, Docker Compose, or something else. Want a custom tweak? Email boileragents@gmail.com and let’s make it happen.

Top comments (0)