Mastering CRUD Operations: Building Dynamic Applications with Java Spring Boot and PostgreSQL

Author Profile Pic
Anurag
Published on Fri Jun 16 2023 ~ 6 min read
Mastering CRUD Operations: Building Dynamic Applications with Java Spring Boot and PostgreSQL

In modern web development, creating applications that interact with databases is a common requirement. The ability to perform CRUD operations (Create, Read, Update, Delete) on a database is essential for building dynamic and data-driven applications. In this article, we will explore how to implement CRUD operations using Java Spring Boot with a PostgreSQL database.


Prerequisites:


Before diving into the implementation, make sure you have the following prerequisites in place:

  1. Java Development Kit (JDK) installed on your machine.
  2. Apache Maven for managing dependencies.
  3. An Integrated Development Environment (IDE) such as IntelliJ or Eclipse.
  4. PostgreSQL database server installed and running.


Setting up the Project:


To begin, let's set up a new Spring Boot project:

  1. Open your IDE and create a new Spring Boot project.
  2. Configure the project with the necessary dependencies. For our case, we will need the following dependencies:
  3. Spring Web: Provides support for building RESTful web services.
  4. Spring Data JPA: Simplifies database access using the Java Persistence API.
  5. PostgreSQL Driver: Allows Spring Boot to connect to a PostgreSQL database.
  6. After setting up the project, create a new package called "model" to hold our data model classes. Within the "model" package, create a class called "User" with attributes like "id," "name," and "email." Annotate the class with @Entity to mark it as a JPA entity.


Implementing the Repository:


Next, we need to define a repository interface to handle database operations. Create a new package called "repository" and create an interface called "UserRepository" within it. The "UserRepository" interface should extend the JpaRepository interface provided by Spring Data JPA and specify the entity class and primary key type. It will handle the basic CRUD operations for the "User" entity.


package com.example.repository;

import com.example.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
}


Implementing the Service Layer:


The service layer acts as a bridge between the repository and the controller. Create a new package called "service" and create a class called "UserService" within it. Annotate the class with @Service to mark it as a Spring service. Inject the UserRepository dependency using the @Autowired annotation. Implement methods in the service class that corresponds to the CRUD operations we want to perform.


package com.example.service;

import com.example.model.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public Optional<User> getUserById(Long id) {
        return userRepository.findById(id);
    }

    public User createUser(User user) {
        return userRepository.save(user);
    }

    public User updateUser(Long id, User userDetails) {
        Optional<User> user = userRepository.findById(id);
        if (user.isPresent()) {
            User existingUser = user.get();
            existingUser.setName(userDetails.getName());
            existingUser.setEmail(userDetails.getEmail());
            return userRepository.save(existingUser);
        }
        return null;
    }

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}


Implementing the Controller:


The controller layer handles the incoming HTTP requests and interacts with the service layer. Create a new package called "controller" and create a class called "UserController" within it. Annotate the class @RestController to mark it as a Spring REST controller. Inject the UserService dependency using the @Autowired annotation. Implement methods in the controller class that corresponds to the CRUD operations we want to expose as API endpoints.


package com.example.controller;

import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/users")
public class UserController {
    private final UserService userService;


    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }


    @GetMapping("/{id}")
    public Optional<User> getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }


    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }


    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        return userService.updateUser(id, userDetails);
    }


    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}



Configuring the Database:


To connect Spring Boot with the PostgreSQL database, open the application.properties file and configure the following properties:


spring.datasource.url=jdbc:postgresql://localhost:5432/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true


Testing the Application:


At this point, our CRUD operations are implemented. We can now test the application using tools like Postman or cURL.

  1. Start your PostgreSQL database server.
  2. Run the Spring Boot application.
  3. Use Postman or any other REST client to interact with the CRUD operations exposed by the controller.


Conclusion:

In this article, we explored how to perform CRUD operations in Java Spring Boot with a PostgreSQL database. We set up the project, implemented the repository, service, and controller layers, and configured the database connection. By following these steps, you can build powerful and scalable applications that interact with a PostgreSQL database using the Java Spring Boot framework.

Comments


Loading...

Post a Comment

Address

Nirvana Apt, Hinjeadi, Pune, Maharastra - 411057 (India)

Website
Site : www.anucodes.in
Social