top of page
Interesting Recent Posts :
Writer's pictureRohit chopra

Springboot with Postgress DB : CRUD Operations


Introduction: Spring Boot is a powerful framework that provides a quick and easy way to develop production-ready applications. One of the most popular use cases for Spring Boot is to create RESTful web services that interact with a database. In this tutorial, we will focus on using Spring Boot with PostgreSQL. PostgreSQL is a popular open-source relational database management system that provides features such as transactions, concurrency control, and advanced indexing. It is widely used in web applications because of its reliability and scalability. To use Spring Boot with PostgreSQL, we will need to add some dependencies and configure our application to use the database. In this tutorial, we will guide you through the process of setting up a Spring Boot application with PostgreSQL. Dependencies: To use Spring Boot with PostgreSQL, we need to add the following dependencies to our pom.xml file:


<dependencies>
    <!-- Spring Boot Starter JDBC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    
    <!-- PostgreSQL JDBC Driver -->
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.2.24</version>
    </dependency>
    
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

The spring-boot-starter-jdbc dependency provides support for JDBC (Java Database Connectivity) which is a standard API for connecting to databases from Java. The postgresql dependency provides the JDBC driver for PostgreSQL. Finally, the spring-boot-starter-web dependency provides support for building web applications. Configuration:

To configure our application to use PostgreSQL, we need to add the following properties to our application.properties file:





spring.datasource.url=jdbc:postgresql://localhost:5432/mydb spring.datasource.username=postgres spring.datasource.password=secret spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.jpa.hibernate.ddl-auto=create-drop 


The spring.datasource.url property specifies the URL of our database, mydb is the name of the database that we will be using. The spring.datasource.username and spring.datasource.password properties specify the username and password for connecting to the database. The spring.datasource.driver-class-name property specifies the JDBC driver class name. The spring.jpa.properties.hibernate.dialect property specifies the Hibernate dialect for PostgreSQL. The spring.jpa.hibernate.ddl-auto property specifies the Hibernate auto-creation strategy for the database schema. Sample Output: Now that we have added the required dependencies and configured our application, we can create a simple RESTful web service that interacts with our PostgreSQL database. Let's create a User entity class:




@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false)
    private String name;
    
    @Column(nullable = false)
    private String email;
    
    // constructors, getters and setters
}


This User entity class represents a user in our system. It has an id, name, and email fields. Now, let's create a UserRepository interface that extends the JpaRepository interface provided by Spring Data JPA:




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


This UserRepository interface provides methods for performing CRUD (Create, Read, Update, and Delete) operations on the User entity. We don't need to provide any implementation for these methods, as Spring Data JPA will generate them automatically for us. Finally, let's create a REST controller that uses the UserRepository to handle HTTP requests:





@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;
    
    @GetMapping
    public List<User> getUsers() {
        return userRepository.findAll();
    }
    
    @PostMapping
    public User createUser(@RequestBody User user) {
        return userRepository.save(user);
    }
    
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
    }
    
    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
        
        user.setName(userDetails.getName());
        user.setEmail(userDetails.getEmail());
        
        return userRepository.save(user);
    }

    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("User", "id", id));
        
        userRepository.delete(user);
        
        return ResponseEntity.ok().build();
    }
}




This UserController class defines REST endpoints for retrieving all users, creating a new user, retrieving a user by ID, updating a user, and deleting a user. We are using the @Autowired annotation to inject the UserRepository into the controller.



To test our application, we can use a tool like Postman to send requests to our RESTful web service. For example, we can send a POST request to create a new user:


POST /users/
{
    "name": "John Doe",
    "email": "john.doe@example.com"
}

If everything is configured correctly, we should receive a response with the created user object:


{
    "id": 1,
    "name": "John Doe",
    "email": "john.doe@example.com"
}

Conclusion:

In this tutorial, we have learned how to use Spring Boot with PostgreSQL. We have added the required dependencies and configured our application to use PostgreSQL. We have also created a simple RESTful web service that interacts with our PostgreSQL database. Spring Boot provides an easy way to create production-ready applications with minimal configuration.

9 views

Recent Posts

See All

SpringBoot -Multithreading Code Example

Introduction: In this post, we'll look at how to implement multithreading in a Spring Boot application using books inventory as an...

Comments


bottom of page