Before starting the example let’s understand what is spring boot, spring data JPA and Postgresql.
What is a Spring boot?
Spring Boot is an open-source Java framework that simplifies the process of creating and deploying standalone, production-grade Spring-based applications. It is built on top of the popular Spring Framework and provides a streamlined development experience by removing the need for boilerplate configuration and infrastructure setup.
What is Spring Data JPA?
Spring Data JPA is a sub-project of the Spring Data framework that provides a convenient way to interact with relational databases using the Java Persistence API (JPA). It aims to simplify database access and reduce boilerplate code by providing a higher-level abstraction for working with databases.
What is PostgreSQL?
PostgreSQL, also known as Postgres, is a powerful open-source object-relational database management system (DBMS). It is widely recognized for its robustness, extensibility, and adherence to SQL standards. PostgreSQL supports a wide range of features and capabilities, making it suitable for various types of applications and workloads.
Technologies used:
- Spring Boot
- Spring
- Hibernate
- HikariCP
- PostgreSQL driver
- Maven
- Java
Here’s an example of a Spring Boot application that uses Spring Data JPA with PostgreSQL as the database. This example demonstrates basic CRUD (Create, Read, Update, Delete) operations on a “User” entity.
First, make sure you have the necessary dependencies in your pom.xml file:
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- PostgreSQL Driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
</dependencies>
Next, create the User entity class representing a table in the PostgreSQL database:
import javax.persistence.*;
@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
// or use lombok
}
Next, create the repository interface for the User entity as UserRepository using Spring Data JPA:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Now, create the REST controller to handle CRUD operations:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable("id") Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id: " + id));
}
@PostMapping
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable("id") Long id, @RequestBody User user) {
user.setId(id);
return userRepository.save(user);
}
@DeleteMapping("/{id}")
public void deleteUser(@PathVariable("id") Long id) {
userRepository.deleteById(id);
}
}
Finally, configure the PostgreSQL database connection in the application.properties or application.yml file:
spring.datasource.url=jdbc:postgresql://localhost:5432/yourdatabasename
spring.datasource.username=yourusername
spring.datasource.password=yourpassword
spring.jpa.hibernate.ddl-auto=update
Make sure to replace yourdatabasename, yourusername, and mypassword with your actual database details.
That’s it! You now have a Spring Boot application using Spring Data JPA with PostgreSQL. You can run this application as a regular Spring Boot application and access the CRUD operations via REST endpoints at http://localhost:8080/users.
Continue Learning