Spring Boot Integration With PostgreSQL as a Maven Project
Last Updated :
09 Oct, 2022
PostgreSQL is a user-friendly versatile RDBMS. This article lets us see how to integrate Spring Data JPA with PostgreSQL. There are some conventions to be followed while using PostgreSQL. We will cover that also.
Working with PostgreSQL
We can easily create databases and tables in that. The below screenshot will help with how to connect to PostgreSQL via the command line
Â
Now let us create a table named "geek_author" under "geeksforgeeks" database.
Note: During table creation, PostgreSQL expects _ as the separator between two words.
Â
Sequence is necessary as we are using "GenerationType.SEQUENCE". Hence we need to create by using
CREATE SEQUENCE hibernate_sequence START 1;
Example Project
Project Structure:
Â
This is the maven project. All dependencies need to be specified under pom.xml. As we are connecting PostgreSQL, this dependency is significant
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
As we are using spring data JPA, this dependency is essential
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
pom.xml
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg.postgresql</groupId>
<artifactId>springboot-postgresql-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-postgresql-sample</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--postgresql dependency -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Let's start with the Model class. Namingwise let it be concurrent with the Postgres table
geek_author.java
Java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "geek_author")
public class geek_author {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private Integer author_id;
private String author_name;
private String email_id;
public Integer getAuthor_id() {
return author_id;
}
public void setAuthor_id(Integer author_id) {
this.author_id = author_id;
}
public String getAuthor_name() {
return author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getEmail_id() {
return email_id;
}
public void setEmail_id(String email_id) {
this.email_id = email_id;
}
}
Let us write the repository class now
AuthorRepository.java
Java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.gfg.postgresql.model.geek_author;
@Repository
public interface AuthorRepository extends JpaRepository<geek_author, Long>{
}
AuthorController.java
Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gfg.postgresql.model.geek_author;
import com.gfg.postgresql.repository.AuthorRepository;
// This means that this
// class is a Controller
@Controller
// This means URL's start with /geek (after Application path)
@RequestMapping(path="/geek")
public class AuthorController {
// This means to get the bean called geekuserRepository
// Which is auto-generated by Spring, we will use it
// to handle the data
@Autowired
private AuthorRepository authorRepository;
// Map ONLY POST Requests
@PostMapping(path="/addauthor")
public @ResponseBody String addAuthors (@RequestParam String author_name
, @RequestParam String email_id) {
// @ResponseBody means the returned String
// is the response, not a view name
// @RequestParam means it is a parameter
// from the GET or POST request
geek_author geekAuthor = new geek_author();
geekAuthor.setAuthor_name(author_name);
geekAuthor.setEmail_id(email_id);
authorRepository.save(geekAuthor);
return "Details got Saved";
}
@GetMapping(path="/authors")
public @ResponseBody Iterable<geek_author> getAllAuthors() {
// This returns a JSON or
// XML with the Book
return authorRepository.findAll();
}
}
Application that can be started is coded as follows :
AuthorApplication.java
Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AuthorApplication {
public static void main(String[] args) {
SpringApplication.run(AuthorApplication.class, args);
}
}
When everything is correct, easily this can be run as a normal Java application
Â
Console Output:
Â
Adding authors: This is done via the POST method in the controller
Let's use the "postman" client to add authors
Â
Retrieving Authors:
We can easily retrieve the author's details as follows:
http://localhost:8080/geek/authors
Â
As we have inserted 3 records already, we are getting all the author details in the above screenshot.
Similar Reads
Spring Boot Kafka Producer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Spring Boot Kafka Consumer Example
Spring Boot is one of the most popular and most used frameworks of Java Programming Language. It is a microservice-based framework and to make a production-ready application using Spring Boot takes very less time. Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applica
3 min read
Message Compression in Apache Kafka using Spring Boot
Generally, producers send text-based data, such as JSON data. It is essential to apply compression to the producer in this situation. Producer messages are transmitted uncompressed by default. There are two types of Kafka compression. 1. Producer-Level Kafka Compression When compression is enabled o
4 min read
Spring Boot - Create and Configure Topics in Apache Kafka
Topics are a special and essential component of Apache Kafka that are used to organize events or messages. In other words, Kafka Topics enable simple data transmission and reception across Kafka Servers by acting as Virtual Groups or Logs that store messages and events in a logical sequence. In this
2 min read
How to Test Spring Boot Project using ZeroCode?
Zerocode automated testing framework for a REST API project concept is getting seen via this tutorial by taking a sample spring boot maven project. Let us see the dependencies for Zerocode : <dependency> <groupId>org.jsmart</groupId> <artifactId>zerocode-tdd</artifactId
5 min read
Validation in Spring Boot
In this article, via a Gradle project, let us see how to validate a sample application and show the output in the browser. The application is prepared as of type Spring Boot and in this article let us see how to execute via the command line as well. Example Project Project Structure: Â As this is th
5 min read
Spring Boot â Validation using Hibernate Validator
Hibernate Validator provides a powerful and flexible way to validate data in Spring Boot applications. Validating user input is essential for building secure and reliable applications. Spring Boot makes this easy with Hibernate Validator, the reference implementation of JSR 380 (Bean Validation API)
6 min read
How to Connect MongoDB with Spring Boot?
In recent times MongoDB has been the most used database in the software industry. It's easy to use and learn This database stands on top of document databases it provides the scalability and flexibility that you want with the querying and indexing that you need. In this, we will explain how we conne
4 min read
Spring Boot - File Handling
Spring Boot is a popular, open-source spring-based framework used to develop robust web applications and microservices. As it is built on top of Spring Framework it not only has all the features of Spring but also includes certain special features such as auto-configuration, health checks, etc. whic
5 min read
Spring Boot MockMVC Testing with Example Project
In a Spring Boot project, we have to test the web layer. For that, we can use MockMVC. In this tutorial, let us see how to do that by having a sample GeekEmployee bean and writing the business logic as well as the test cases for it. Example Project Project Structure: Â This is a maven project. Let's
5 min read