Connect docker container to spring boot app

Viewed 21

I'm following a tutorial to create a mild spring boot application. I am running the IntelliJ community edition. I want to connect a docker container running Postgresql to the application. The idea is that there is a person database which has two tables for a name and id. I want to connect the person database with the spring boot app so I can run queries against it. https://youtu.be/vtPkZShrvXQ?t=4309

I ran a docker-compose in terminal to create the container, then installed the docker extension on IntelliJ. I am new to this so please be patient. I am willing to redo if there are better approaches. I have attached source code for my controller, the link of the tutorial, an image of docker container running in IntelliJ, and an image of my docker-compose.yml file.

@RequestMapping("api/v1/person")
@RestController
public class PersonController {
    private final PersonService personService;

    @Autowired
    public PersonController(PersonService personService) {
        this.personService = personService;
    }
    @PostMapping
    public void addPerson(@RequestBody Person person){
        personService.addPerson(person);
    }
    @GetMapping
    public List<Person> getAllPeople(){
        return personService.getAllPeople();
    }
    @GetMapping(path="/{id}")
    public Person getPersonById(@PathVariable("id") UUID id){
        return personService.getPersonById(id)
                .orElse(null);
    }
    @DeleteMapping(path="{id}")
    public void deletePerson(@PathVariable("id") UUID id){
        personService.deletePerson(id);
    }
    @PutMapping(path="{id}")
    public void updatePerson(@PathVariable("id") UUID id, @RequestBody Person personToUpdate){
        personService.updatePerson(id,personToUpdate);
    }
}

docker container running docker-compose.yml

1 Answers

You have to use Spring Data starter with postgres sql driver

Add following dependencies:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
</dependency>


  <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

application.properties:

## default connection pool
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5

## PostgreSQL
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres-spring
spring.datasource.password=password

#drop n create table again, good for testing, comment this in production
spring.jpa.hibernate.ddl-auto=create
Related