0Pricing
Spring Boot 4 Microservices & REST APIs · درس

عمليات CRUD باستخدام REST

طبّق عمليات الإنشاء والقراءة والتحديث والحذف لكياناتك عبر نقاط نهاية REST.

عمليات CRUD باستخدام REST درس مجاني في Spring Boot 4 Microservices & REST APIs على CoddyKit. هذا هو الدرس 5 من أصل 6. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Microservices & REST APIs، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Microservices & REST APIs 6 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

CRUD Operations: The Basics

Welcome to implementing CRUD operations with Spring Boot! CRUD stands for Create, Read, Update, and Delete.

These are the four fundamental operations for persistent storage, allowing you to manage data in your application.

In REST APIs, each CRUD operation typically maps to a specific HTTP method.

Mapping CRUD to HTTP Methods

Understanding how CRUD maps to HTTP methods is key for RESTful design:

  • Create (C): Handled by POST requests.
  • Read (R): Handled by GET requests.
  • Update (U): Handled by PUT requests.
  • Delete (D): Handled by DELETE requests.

We'll use a simple Product entity and its ProductRepository from previous lessons.

Implementing Create (POST)

To create a new resource, we use the POST HTTP method. In Spring Boot, this is handled by the @PostMapping annotation.

The new product data is sent in the request body, which Spring automatically maps to our Product object using @RequestBody.

Create Product Example

Here's how you'd create an endpoint to add a new product. Run it, then try adding a product via a tool like Postman (e.g., POST to /api/products with JSON body {"name": "Laptop", "price": 1200.0}).

package com.coddykit.crud;

import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

@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;
    }
    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; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@RestController
@RequestMapping("/api/products")
class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @PostMapping
    public Product createProduct(@RequestBody Product product) {
        return productRepository.save(product);
    }
}

@SpringBootApplication
class CrudApplication {
    public static void main(String[] args) {
        SpringApplication.run(CrudApplication.class, args);
    }
}

Implementing Read (GET)

Reading resources is done with the GET HTTP method. We'll create two types of read operations:

  • Get all products: Maps to @GetMapping.
  • Get a single product by ID: Maps to @GetMapping("/{id}") using a @PathVariable.

When fetching by ID, we use Optional to handle cases where the product might not exist.

Read Products Example

This code adds methods to fetch all products and a single product by its ID. Notice the use of ResponseEntity to return a 404 if a product isn't found.

package com.coddykit.crud;

import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import java.util.List;
import java.util.Optional;

@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;
    }
    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; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@RestController
@RequestMapping("/api/products")
class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @GetMapping
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        Optional<Product> product = productRepository.findById(id);
        return product.map(ResponseEntity::ok)
                      .orElseGet(() -> ResponseEntity.notFound().build());
    }
}

@SpringBootApplication
class CrudApplication {
    public static void main(String[] args) {
        SpringApplication.run(CrudApplication.class, args);
    }
}

Implementing Update (PUT)

To update an existing resource, we use the PUT HTTP method, annotated with @PutMapping.

The endpoint typically includes the resource's ID in the path (/{id}) to identify which item to update, and the updated data is sent in the @RequestBody.

Update Product Example

This method updates an existing product. It first checks if the product exists using the ID from the path. If found, it updates the fields from the request body and saves it.

package com.coddykit.crud;

import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import java.util.Optional;

@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;
    }
    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; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@RestController
@RequestMapping("/api/products")
class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(
        @PathVariable Long id, @RequestBody Product productDetails) {
        Optional<Product> product = productRepository.findById(id);
        if (product.isPresent()) {
            Product existingProduct = product.get();
            existingProduct.setName(productDetails.getName());
            existingProduct.setPrice(productDetails.getPrice());
            return ResponseEntity.ok(productRepository.save(existingProduct));
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

@SpringBootApplication
class CrudApplication {
    public static void main(String[] args) {
        SpringApplication.run(CrudApplication.class, args);
    }
}

Implementing Delete (DELETE)

To remove a resource, we use the DELETE HTTP method, annotated with @DeleteMapping.

Similar to update, the ID of the resource to delete is passed as a @PathVariable. After deletion, it's common to return a 204 No Content status.

Delete Product Example

This method deletes a product by ID. It finds the product and, if present, deletes it. Returning ResponseEntity.noContent().build() is a good practice for successful deletions.

package com.coddykit.crud;

import jakarta.persistence.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import java.util.Optional;

@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;
    }
    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; }
}

@Repository
interface ProductRepository extends JpaRepository<Product, Long> {}

@RestController
@RequestMapping("/api/products")
class ProductController {
    @Autowired
    private ProductRepository productRepository;

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        Optional<Product> product = productRepository.findById(id);
        if (product.isPresent()) {
            productRepository.delete(product.get());
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

@SpringBootApplication
class CrudApplication {
    public static void main(String[] args) {
        SpringApplication.run(CrudApplication.class, args);
    }
}

Quick Check: HTTP Methods

Which HTTP method is typically used to update an existing resource in a REST API, and which one is for creating a new resource?

Recap: CRUD with REST

You've successfully learned how to implement all four CRUD operations using Spring Boot REST controllers!

  • Create: Use @PostMapping.
  • Read: Use @GetMapping (for all or by ID).
  • Update: Use @PutMapping.
  • Delete: Use @DeleteMapping.

These are the building blocks for almost any data-driven API. Next, we'll explore validation and error handling!

الأسئلة الشائعة

هل درس «عمليات CRUD باستخدام REST» مجاني؟

نعم — نص درس «عمليات CRUD باستخدام REST» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Microservices & REST APIs، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Microservices & REST APIs 6 دروس في المجموع.

ماذا ستتعلم في «عمليات CRUD باستخدام REST»؟

طبّق عمليات الإنشاء والقراءة والتحديث والحذف لكياناتك عبر نقاط نهاية REST. تتمرن على Spring Boot 4 Microservices & REST APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Microservices & REST APIs؟

لا تُشترط خبرة سابقة. Spring Boot 4 Microservices & REST APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 5 من أصل 6.

كم من الوقت يستغرق درس «عمليات CRUD باستخدام REST»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Microservices & REST APIs هذا؟

نعم. كل درس في Spring Boot 4 Microservices & REST APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. دمج قاعدة بيانات H2 وJPA
  2. مقدمة إلى Spring Data JPA
  3. إنشاء الكيانات والمستودعات
  4. تعريف الكيانات والمستودعات
  5. عمليات CRUD باستخدام REST
  6. تنفيذ عمليات CRUD
← العودة إلى Spring Boot 4 Microservices & REST APIs