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

Leave a Reply

Your email address will not be published. Required fields are marked *