Introduction
In this tutorial, you will learn how to create a RESTful CRUD API using Spring Boot, PostgreSQL as the database, and JPA with Hibernate for object-relational mapping. We’ll cover each step with detailed code examples, allowing you to build a robust API quickly and efficiently.
Prerequisites
Before you begin, ensure you have the following installed:
- Java Development Kit (JDK)
- Spring Boot
- PostgreSQL
- IDE (Eclipse, IntelliJ IDEA, etc.)
Step 1: Set Up the Project
First, let’s set up a new Spring Boot project.
spring init --name spring-boot-postgresql-crud-api --dependencies web,data-jpa,postgresql
Step 2: Configure PostgreSQL Database
Next, configure PostgreSQL as the database. Open application.properties
and add:
spring.datasource.url=jdbc:postgresql://localhost:5432/db_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.hibernate.ddl-auto=update
Replace db_name
, your_username
, and your_password
with your PostgreSQL database details.
Step 3: Create Entity Class
Create an entity class representing the data model. For example, let’s create a Product
entity.
import javax.persistence.*;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private double price;
// Getters and setters
}
Step 4: Create Repository Interface
Create a repository interface for the entity to perform CRUD operations.
import org.springframework.data.jpa.repository.JpaRepository;
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Step 5: Create REST Controller
Now, create a REST controller to handle HTTP requests.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping
public List<Product> getAllProducts() {
return productRepository.findAll();
}
@PostMapping
public Product createProduct(@RequestBody Product product) {
return productRepository.save(product);
}
@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product", "id", id));
}
@PutMapping("/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product", "id", id));
product.setName(productDetails.getName());
product.setPrice(productDetails.getPrice());
return productRepository.save(product);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteProduct(@PathVariable Long id) {
Product product = productRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Product", "id", id));
productRepository.delete(product);
return ResponseEntity.ok().build();
}
}
Step 6: Run the Application
Finally, run the Spring Boot application and test the CRUD API endpoints using tools like Postman or cURL.
mvn spring-boot:run
That’s it! You’ve successfully built a RESTful CRUD API using Spring Boot, PostgreSQL, JPA, and Hibernate.
Feel free to expand upon this example by adding validation, error handling, security, or additional endpoints as needed. Happy coding!