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
@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
In this blog using the Spring WebFlux module, we are going to leverage the functional…
Spring Cloud Function is a project within the Spring ecosystem that allows developers to build…
RabbitMQ is an open-source message broker software that implements the Advanced Message Queuing Protocol (AMQP).…
Spring Integration is a powerful extension of the Spring Framework designed to support the implementation…
The Spring Cloud Config Client is a component of the Spring Cloud framework that enables…
In Python, handling CSV (Comma Separated Values) files is easy using the built-in csv module.…