0% found this document useful (0 votes)
37 views11 pages

Spring Boot with PostgreSQL Setup Guide

This document provides instructions for setting up a Postgres database with sample data and connecting it to a Spring Boot application. It discusses installing Postgres, configuring roles and connections, creating a sample "accounts" table, developing the Spring Boot project including entities, repositories, services and controllers, and executing GET requests to retrieve account data from the database. Custom queries are also demonstrated to filter results based on request parameters. The goal is to establish this setup for exploring more advanced database concepts in future tutorials.

Uploaded by

Gonzalo Scarpa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views11 pages

Spring Boot with PostgreSQL Setup Guide

This document provides instructions for setting up a Postgres database with sample data and connecting it to a Spring Boot application. It discusses installing Postgres, configuring roles and connections, creating a sample "accounts" table, developing the Spring Boot project including entities, repositories, services and controllers, and executing GET requests to retrieve account data from the database. Custom queries are also demonstrated to filter results based on request parameters. The goal is to establish this setup for exploring more advanced database concepts in future tutorials.

Uploaded by

Gonzalo Scarpa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Getting Started With Spring Boot With

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.

 Now we can log in using a user that we created.

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

 The bare minimum requirement is just a hostname, port, database, username,


and password.
 on the local system, the hostname would be localhost. the default port is 5432
unless you have set a custom port. we are using the default postgres database
and username/password we created above as admin/root
Setup Postgres Sample Data
Create Accounts Table

CREATE TABLE accounts (


user_id serial PRIMARY KEY,
username VARCHAR ( 50 ) UNIQUE NOT NULL,
password VARCHAR ( 50 ) NOT NULL,
email VARCHAR ( 255 ) UNIQUE NOT NULL,
created_on TIMESTAMP NOT NULL,
last_login TIMESTAMP
);

Insert Rows

 Simple insert row command would look like below


insert into accounts (username, password, email, created_on,
last_login) values('user2', 'password1234', 'abc1@[Link]', now(),
now());

 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, '@[Link]'), now(), now());
end loop;
end ; $$

 Now let's select the rows from the account table to verify if the inserts were
successful

select * from accounts;

 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.

Operating Database with PSQL


 We can perform all the above operations using the command line as well.

Connecting to database

Listing all the databases


Switching database & Listing Tables

Describing the schema of the table

Selecting all the records from the table

Sprint Boot Project


 Goto [Link] and create the project name “spring-postgres”.
 I like maven as a build tool so I selected that but you can choose Gradle as well.
 I chose the java 17 version since that's the latest I have on my machine.
 Add dependencies such as Spring web, Spring data jpa,
 Also, add postgres driver in order to connect to postgres database. the easiest
way is to add the dependency in [Link]

<dependency>
<groupId>[Link]</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

Configure Database Connection


 I am using IntelliJ IDEA to open this project, you can use it with any idea that
you are comfortable with (Eclipse, Netbeans, or even VSCode )
 The first thing that we have to do is to set up the database connection
configuration in a resource file called [Link]

[Link]=jdbc:postgresql://localhost:5432/postgres
[Link]=admin
[Link]=root

Write Application Code


Entity

 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;

//...... more code

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 [Link];

import [Link];
import [Link];

public interface AccountRepository extends JpaRepository<Account,


Integer> {

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;

public List<Account> getAccounts(){


return [Link]();
}

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 [Link]();
}
}

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
[Link]
 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

 Curl command returns a list of all the accounts


we can also see the result in the browser

Write First Custom Query


 In this section, we will see how we can write custom queries in spring boot.
 We can use @Query provided by spring data jpa to execute the JPA query. The
below example is just returning userId greater or equal to the passed integer
value.
 We will take this integer from the user as a rest request and pass it as an
argument to this query method.

public interface AccountRepository extends JpaRepository<Account,


Integer> {

@Query("select a from Account a where [Link] >= :userId")


List<Account> findAllWithFilteredUserId(
@Param("userId") Integer userId);
}

Logic

public List<Account> getConditionalAccount(Integer userId){


return [Link](userId);
}
Controller

 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 [Link](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]

Common questions

Powered by AI

Spring Boot can be extended to handle advanced database concepts such as sharding or partitioning with PostgreSQL by customizing its configuration. Implementing sharding might involve setting up multiple databases or instances, each responsible for a specific data segment, and directing queries to the appropriate instance. Spring Boot can manage these connections using additional configurations and custom routing logic. Partitioning can be achieved within PostgreSQL using its native support, managed through Spring Data JPA by defining entities that align with the partitioned tables. Advanced transactions and query management can further optimize performance and ensure the consistency of distributed data .

The basic steps to set up a PostgreSQL database for integration with a Spring Boot application include installing PostgreSQL, configuring it with a role and a user, and setting up a sample database schema. Afterward, using a GUI tool like PGAdmin to manage the database is recommended. In the Spring Boot application, dependencies such as Spring Data JPA and the PostgreSQL driver need to be added in the pom.xml file. The database connection is configured through a resource file such as application.properties, specifying the URL, username, and password .

Using Spring Boot’s REST API to serve data from a PostgreSQL database offers several advantages, including ease of setup and development due to Spring Boot’s convention-over-configuration approach. It provides built-in support for RESTful services and simplifies data access through JPA. Additionally, Spring Boot offers extensive integration with other technologies and quick deployment, providing scalable APIs that can efficiently handle requests to retrieve or modify data stored in PostgreSQL .

Creating a Spring Boot project configured for PostgreSQL using IntelliJ IDEA involves several steps. First, you go to start.spring.io to configure a new project with necessary dependencies like Spring Web and Spring Data JPA, then download the generated project structure. In IntelliJ IDEA, open the project and configure the database connection in the application.properties file. Add the PostgreSQL dependency in the pom.xml file and create your database schema along with the entity classes, repository interfaces, and controller classes to manage data interactions via REST API .

Repository patterns in Spring Boot’s JPA implementation promote application scalability by abstracting data access layers, which facilitates separation of concerns and cleaner code bases. This pattern simplifies database interactions, allowing developers to focus on business logic rather than database specifics. When connected to PostgreSQL, this ensures efficient querying, by possibly leveraging query derivation and JPA’s caching strategies, which can reduce database load and improve performance, particularly in applications with high concurrency demands .

The @Query annotation in a Spring Boot application using JPA allows the definition of custom SQL queries directly within the repository interface. This is useful when needing to execute complex queries that go beyond the basic CRUD operations provided by JpaRepository. The @Query annotation can be parameterized to accept arguments from method parameters, supporting dynamic query execution based on user inputs .

In a Spring Boot application, database operations are managed using the Spring Data JPA. The entity class is annotated with @Entity and @Table to map the database table to a Java object. A Repository interface extending JpaRepository is created to handle basic CRUD operations, enabling the application to interact with PostgreSQL without writing SQL code. The service layer will typically use this repository to perform database operations, while the controller handles HTTP requests and responses .

Dependency management in a Spring Boot project is facilitated through build tools like Maven or Gradle. By specifying dependencies such as Spring Data JPA and the PostgreSQL driver in the pom.xml or build.gradle files, Spring Boot automatically manages the libraries needed for the application, including their versions and transitive dependencies. This automation simplifies integration with PostgreSQL by ensuring that the correct libraries are included, reducing configuration errors and improving compatibility across different environments .

Loops can be used in PostgreSQL to automate the generation of multiple sample data records. By using a loop, such as the DO block, you can insert repetitive patterns or incrementing values by iterating through a predefined range. This method is efficient for preparing test data scenarios and allows developers to quickly populate tables with a large amount of data, which is beneficial when developing, testing, or demonstrating a Spring Boot application that interacts with a PostgreSQL database .

Command-line tools provide greater control and flexibility for scripting and automating database tasks but require more expertise and familiarity with SQL syntax. GUI tools like PGAdmin provide a more user-friendly, visual interface that simplifies database management tasks such as creating tables, querying data, and performing CRUD operations. In a Spring Boot project, using a GUI tool can accelerate development by simplifying tasks like schema design and modifications, while command-line tools might be preferred for streamlined deployment or automated scripts .

You might also like