Connecting your Spring API to Postgres

    I recently was going through these videos on PluralSight to learn some Spring API concepts, and ran into some trouble getting my API to connect to my database. The video glossed over connecting to the database, but I followed some instructions on getting Postgres on Docker. Try as I may, I continually got errors saying I either had the wrong password or that no password was offered. Eventually I realized the Docker container was on the same port as my local Postgres instance, but even when I changed the port I got a whole new JPA error. Since I knew I could connect to the local Postgres instance, I created a new database there instead.

    The videos directed me to a GitHub repository where I was able to find some SQL scripts for creating tables and inserting the data. These were easy to run in Docker, but to run them in PSQL I needed to learn a few easy commands. PSQL uses the '\' character plus another letter to run commands, for example '\l' (that's an L by the way, that caused no shortage of confusion for me at first) lists all the available databases. '\c' plus the name of a database lets you access the database. '\dt' displays all of the available tables in that database, and then you can use regular query commands to access data. I simply pasted my scripts for creating tables and then inserting data, and I very quickly had my database up and running.

    The next thing was getting connected. In my file I had to add the following lines of code (of course if you wanted to be really smart you would store these values as environment variables). 'Database' will be the name of your database, 'username' and 'password' will be your username and password, and they do not need to be in quotes.

     I'm using JPA as a black box a little bit, since I've only scrape the surface of what it offers but so far it's been pretty neat. You'll need to add some dependencies in your pom.xml file that look a bit like this:


    Once that was taken care of, I sent a Get request to my project that was running and was able to see Spring make use of my Postgres database! My full code is available here if you'd like to check it out.


Popular posts from this blog

API's in C#

Using WebRTC to build a videophone in React and TypeScript

Reviewing WPF and MVVM