Performing CRUD Operations
Implement Create, Read, Update, and Delete operations using Spring Data JPA's powerful repository methods.
CRUD Operations: The Core
Welcome to the heart of data management! Today, we'll master CRUD operations with Spring Data JPA. CRUD is a fundamental concept for almost any application that interacts with a database.
- Create: Adding new data.
- Read: Retrieving existing data.
- Update: Modifying existing data.
- Delete: Removing data.
Spring Data JPA provides powerful, easy-to-use methods for all of these!
Our Example Setup: Product
To demonstrate CRUD, we'll use a simple Product entity and its corresponding repository. You would have learned to set these up in previous lessons.
Here's our basic Product entity and ProductRepository interface:
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private double price;
public Product() {}
public Product(String name, double price) {
this.name = name;
this.price = price;
}
// Getters and Setters (omitted for brevity)
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
@Override
public String toString() {
return "Product{id=" + id + ", name='" + name + "', price=" + price + "}";
}
}
// ProductRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}