ข้ามไปที่เนื้อหาหลัก

เรื่องที่แนะนำ

คู่มือ Java ฉบับทันสมัย (อัปเดตล่าสุดปี 2025)

 คู่มือ Java ฉบับทันสมัย (อัปเดตล่าสุดปี 2025) บทนำ Java ยังคงเป็นภาษายอดนิยมที่ได้รับความนิยมอย่างต่อเนื่องตั้งแต่ยุค 1990 จนถึงปัจจุบัน ในปี 2025 Java ได้ก้าวหน้าอย่างมากทั้งด้านภาษาหลักและเครื่องมือสนับสนุน ล่าสุด Java 24 ได้เปิดตัวออกมาแล้ว และ Java 21 เป็นเวอร์ชัน LTS (Long-Term Support) ที่แนะนำให้ใช้งานสำหรับระบบจริงในระยะยาว บทความนี้จะช่วยให้คุณเข้าใจภาพรวมของ Java เวอร์ชันล่าสุด รวมถึงฟีเจอร์เด่น โครงสร้างภาษาที่ควรรู้ และแนวทางการพัฒนา Java ยุคใหม่ ภาพรวมเวอร์ชัน Java ล่าสุด เวอร์ชัน สถานะ วันเปิดตัว Java 24 เวอร์ชันล่าสุด มีนาคม 2025 Java 21 เวอร์ชัน LTS ล่าสุด กันยายน 2023 Java 17 LTS รุ่นก่อนหน้า กันยายน 2021 Java 11 LTS เก่า กันยายน 2018 โครงสร้างพื้นฐานของภาษา Java คลาสและอ็อบเจกต์ : โครงสร้างหลักของโปรแกรม Java Primitive Types : int, double, char, boolean เป็นต้น Control Statements : if, switch, while, for, do-while Methods : การแยกโค้ดเป็นหน่วยที่นำกลับมาใช้ซ้ำได้ Array และ Collection : จัดเก็บและจัดการข้อมูลหลายรายการ Exception Handling : try-catch-finally OOP Co...

สอนสร้างระบบ Blog พร้อมระบบ Comment ด้วย Spring Boot

การสร้างระบบ Blog พร้อมระบบ Comment ด้วย Spring Boot

1. เตรียมโครงสร้างโปรเจค

  1. สร้างโปรเจค Spring Boot ใหม่ผ่าน Spring Initializr พร้อมเพิ่ม dependencies ดังนี้:
    • Spring Web
    • Spring Data JPA
    • Spring Boot DevTools
    • H2 Database (หรือ MySQL หากต้องการ)
    • Spring Security (ตัวเลือกสำหรับ Authentication)
  2. ตั้งค่าไฟล์ application.properties:
    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.driver-class-name=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
    spring.h2.console.enabled=true
                

2. สร้าง Entity

2.1 BlogPost Entity

import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
public class BlogPost {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;
    private String content;

    @OneToMany(mappedBy = "blogPost", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Comment> comments = new ArrayList<>();

    // Getter และ Setter
}

2.2 Comment Entity

import jakarta.persistence.*;

@Entity
public class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String content;

    @ManyToOne
    @JoinColumn(name = "blog_post_id", nullable = false)
    private BlogPost blogPost;

    // Getter และ Setter
}

3. สร้าง Repository

3.1 BlogPostRepository

import org.springframework.data.jpa.repository.JpaRepository;

public interface BlogPostRepository extends JpaRepository<BlogPost, Long> {
}

3.2 CommentRepository

import org.springframework.data.jpa.repository.JpaRepository;

public interface CommentRepository extends JpaRepository<Comment, Long> {
}

4. สร้าง Service

4.1 BlogPostService

import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BlogPostService {
    private final BlogPostRepository blogPostRepository;

    public BlogPostService(BlogPostRepository blogPostRepository) {
        this.blogPostRepository = blogPostRepository;
    }

    public List<BlogPost> getAllPosts() {
        return blogPostRepository.findAll();
    }

    public BlogPost getPostById(Long id) {
        return blogPostRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Post not found"));
    }

    public BlogPost createPost(BlogPost blogPost) {
        return blogPostRepository.save(blogPost);
    }
}

4.2 CommentService

import org.springframework.stereotype.Service;

@Service
public class CommentService {
    private final CommentRepository commentRepository;

    public CommentService(CommentRepository commentRepository) {
        this.commentRepository = commentRepository;
    }

    public Comment addComment(Comment comment) {
        return commentRepository.save(comment);
    }
}

5. สร้าง Controller

5.1 BlogPostController

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/posts")
public class BlogPostController {
    private final BlogPostService blogPostService;

    public BlogPostController(BlogPostService blogPostService) {
        this.blogPostService = blogPostService;
    }

    @GetMapping
    public List<BlogPost> getAllPosts() {
        return blogPostService.getAllPosts();
    }

    @GetMapping("/{id}")
    public BlogPost getPostById(@PathVariable Long id) {
        return blogPostService.getPostById(id);
    }

    @PostMapping
    public BlogPost createPost(@RequestBody BlogPost blogPost) {
        return blogPostService.createPost(blogPost);
    }
}

5.2 CommentController

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/comments")
public class CommentController {
    private final CommentService commentService;

    public CommentController(CommentService commentService) {
        this.commentService = commentService;
    }

    @PostMapping
    public Comment addComment(@RequestBody Comment comment) {
        return commentService.addComment(comment);
    }
}

6. ทดสอบระบบ

รันแอปพลิเคชันและเข้าถึง H2 Console ได้ที่ http://localhost:8080/h2-console

ใช้ Postman หรือ curl เพื่อตรวจสอบ REST API:

  • สร้างโพสต์ใหม่:
    POST /api/posts
    {
        "title": "First Post",
        "content": "This is the content of the first post"
    }
  • เพิ่มความคิดเห็น:
    POST /api/comments
    {
        "content": "Great post!",
        "blogPost": {
            "id": 1
        }
    }

7. สรุป

ระบบ Blog พร้อม Comment ด้วย Spring Boot เป็นตัวอย่างที่ดีในการเรียนรู้การพัฒนา REST API และการใช้งาน JPA กับความสัมพันธ์ระหว่าง Entity เช่น OneToMany และ ManyToOne คุณสามารถพัฒนาระบบเพิ่มเติม เช่น การเพิ่ม Authentication, Pagination หรือผสานกับ UI Framework อย่าง React หรือ Angular

ความคิดเห็น

บทความที่ได้รับความนิยม