Setting Up the Database

For our application, we’ll be using PostgreSQL as our database. We’ll set it up using Docker for ease of use and consistency across different development environments.

Setting Up PostgreSQL with Docker Compose

  1. Create a docker-compose.yml file in your project root with the following content:

    version: '3.8'
    services:
      db:
        image: postgres:15
        environment:
          POSTGRES_DB: myapp
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: [CHANGE_THIS_PASSWORD]
        ports:
          - "5432:5432"
        volumes:
          - postgres_data:/var/lib/postgresql/data
    
    volumes:
      postgres_data:
    

    Note

    NB! Make sure to change [CHANGE_THIS_PASSWORD] to a secure password of your choice.

  2. To start the database, run the following command in your terminal:

    docker-compose up -d
    

    The -d flag runs the container in detached mode.

  3. To stop the database when you’re done, use:

    docker-compose down
    

Configuring Spring Boot to Use PostgreSQL

  1. Add the PostgreSQL driver dependency to your build.gradle file:

    dependencies {
        implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
        runtimeOnly 'org.postgresql:postgresql'
    }
    
  2. Configure the database connection in your application.properties file:

    spring.datasource.url=jdbc:postgresql://localhost:5432/myapp
    spring.datasource.username=postgres
    spring.datasource.password=[CHANGE_THIS_PASSWORD]
    
    spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
    spring.jpa.hibernate.ddl-auto=update
    

    Note

    NB! Replace [CHANGE_THIS_PASSWORD] with the same password you used in the Docker Compose file.