Connecting to a real database in Spring Boot isn’t much config — just add the connection details
to application.properties:
spring.datasource.name=spring.datasource.url=spring.datasource.username=spring.datasource.password=For Postgres, install it locally and create a DB for the project (or use Docker instead).
The schema.sql file is picked up automatically by embedded databases (H2) — for a real database
you have to opt in explicitly:
spring.sql.init.mode=alwaysThere are several ways to connect to a real DB — locally installed, Docker, Docker Compose. Using
the Docker approach: on start.spring.io, add the Postgres driver dependency and the Docker Compose
dependency. The latter looks at your other selected dependencies (Postgres) and generates a
compose.yaml for you.
JDBC vs. Spring Data JPA
With JDBC you write your own SQL queries. With JPA, Hibernate handles that as an ORM. To use
Spring Data JPA, add the dependency, then make your repository extend ListCrudRepository (returns
a List) or CrudRepository (returns an Iterable) — both provide standard CRUD out of the box.
Both take two type parameters: the entity type, and its id type.
public interface RunRepository extends ListCrudRepository<Run, Integer> {}That’s it for basic CRUD. For something custom — say, finding runs by location — add a method to the same repository:
// RunRepositorypublic interface RunRepository extends ListCrudRepository<Run, Integer> { List<Run> findAllByLocation(String location);}And expose it from the controller:
// RunController — location as a path variable here, though it could be a query param too@GetMapping("/location/{location}")List<Run> findByLocation(@PathVariable String location) { return runRepository.findAllByLocation(location);}