Getting Started With Spring Boot With Postgres
Getting Started With Spring Boot With Postgres
Postgres
Beginners Guide to Using Postgres with Spring Boot
Introduction
The goal of this article is to set up a Postgres database with sample data and then
use Spring boot to connect with the database and serve data to the end user as
the rest endpoint.
Note that this article is beginner-friendly. All the codes have been made
available on GitHub
In future articles, I will use this setup to demonstrate some of the advanced
databases, and JPA concepts ( associations, partitioning, sharding, transactions,
etc) using the help of setup performed in this article.
Install Postgres
Install Postgres Database
I have a mac environment so my commands are most suitable for mac. i believe
there are equivalent tools to install on the respective environment like windows
and Linux.
#install database
brew install postgresql
# start database
brew services start postgresql
Configure
Once we started the service, we can log in to the default postgres database
We need to configure Postgres with a role for our default postgres database.
Install PGAdmin
PGAdmin is a nice GUI tool that helps us to interact and operate over our
postgres database server.
I downloaded the package here for mac. but you can find appropriate for your
environment.
Once installation is done we can set up a connection to our database.
Setup connection string
Insert Rows
But let's add more rows to the table so that we have more data to play with
We are using a loop to generate multiple rows.
do $$
begin
for index in 3..10 loop
insert into accounts (username, password, email, created_on,
last_login) values( concat('user', index), 'password1234',
concat('abc', index, '@gmail.com'), now(), now());
end loop;
end ; $$
Now let's select the rows from the account table to verify if the inserts were
successful
Now our sample dataset is ready which we can connect with the application and
build API on top of it and return as best response.
Connecting to database
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=admin
spring.datasource.password=root
We will create an entity that will map the database table to Java Object.
@Entity
@Table(name="ACCOUNTS")
public class Account {
@Id @GeneratedValue
private int userId;
private String username;
private String password;
private String email;
private Date createdOn;
private Date lastLogin;
Repository
Next, we will create a repository interface, which will provide all the basic
CRUD capabilities to execute against postgres database.
It's very simple using Spring data jpa, we just need to extend JpaRepository
Interface and pass the Entity name and primary_key.
Check out this file if you are interested.
package com.example.springpostgres.dao;
import com.example.springpostgres.entity.Account;
import org.springframework.data.jpa.repository.JpaRepository;
Logic/Service
Now, we will create a logic/service class. The job of this class is to house
business logic if any.
Our Logic class does not include any business logic, as of now just uses a
repository object to query the database and return the result.
@Service
public class AccountLogic {
@Autowired
private AccountRepository accountRepository;
Controller
Now we are ready to create a controller that will handle user requests and return
the appropriate responses.
We will create AccountController, it has one get endpoint account that returns a
list of accounts in postgres table.
@RestController
@RequestMapping("/accounts")
public class AccountController {
@Autowired
private AccountLogic accountLogic;
@GetMapping()
@ResponseBody()
public List<Account> account(){
return accountLogic.getAccounts();
}
}
Execution
We can execute the main method of SpringPostgresApplication class. The
default port would 8080 and the endpoint that will be available to us would be
http://localhost:8080/accounts
You will see below message when application started successfully after running
main method of SpringPostgresApplication.
If you are using IntelliJ IDEA, you will see the terminal at the bottom tab and
now we can use it to run the curl command.
Output
Logic
For the controller in request we are passing the userId param which is an integer
and filter endpoint basically listening to the request.
@GetMapping("/filter")
@ResponseBody()
public List<Account> accountWithCondition(@RequestParam Integer
userId){
return accountLogic.getConditionalAccount(userId);
}
Curl Request
For the curl request, I am passing userId as the path parameter and we can see
that we are only seeing the result where userid is 5 or more
Code Repository
As usual, I added a code repository to the github.
Conclusion
In this article, we set up the Postgres database and serve the data using spring
boot rest API.
We also learn how to write custom SQL queries to fetch the data from the
Postgres database.
In future articles, we will use this setup to learn about some advanced concepts
like ( associations, partitioning, sharding, transactions, etc)
BestSeller Course
If you want to learn spring boot 3 and spring boot 6, please check out this best seller
and highest rated course. [ 38 hrs content, 4.7/5 stars, 6+ students already enrolled]