Categories: Uncategorised

Spring Boot PostgreSQL Example

PostgreSQL is a powerful , open source relational database system. In this post we will see how to build REST API using Spring Boot with PostgreSQL database.

From the Spring initializr create a project with the below shown dependencies

To configure Spring Boot to use postgreSQL:

spring.datasource.url=jdbc:postgresql://localhost:5432/School
spring.datasource.username=${USERNAME}
spring.datasource.password=${PASSWORD}
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto = update

Entity:

package com.example.postgresdemo.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
 
 @Id
 private int rollNumber;
 
 private String name;
 
 private int age;
}

Let’s create StudentRepository

public interface StudentRepository extends JpaRepository<Student, Integer>{

}

Defined below API’s

  1. Add a Student
  2. Get all Students

@RestController
public class PostgresdemoController {
 
 @Autowired
 StudentService service;
 
 @PostMapping("/Student")
 public Student add(@RequestBody Student student) {
  return service.addStudent(student);
  
 }
 
 @GetMapping("/Student")
 public List<Student> getAll() {
  return service.getAllStudents();
  
 }

}

Service layer:

@Service
public class StudentServiceImpl implements StudentService{
 
 @Autowired
 StudentRepository repository;

 public Student addStudent(Student student) {
  return repository.save(student);
 }

 @Override
 public List<Student> getAllStudents() {
  return repository.findAll();
 }
}

Added couple of students using add API through postman. Presented below the table view from postgreSQL database.

Source Code: https://github.com/MMahendravarman/Springboot_Examples

mahendravarman.m@gmail.com

Recent Posts

Spring Webflux Functional Endpoint – File Upload

In this blog using the Spring WebFlux module, we are going to leverage the functional…

12 months ago

Serverless Functions with Spring Cloud Function, AWS Lambda

Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…

12 months ago

Spring Boot + RabbitMQ – Decoupling Microservices Communication

RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…

12 months ago

Spring Integration – Sending files over SFTP

Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…

1 year ago

Spring Cloud Config Client

The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…

1 year ago

Handling CSV in Python

In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…

1 year ago