DEV Community

Wit
Wit

Posted on

การใช้ Spring Data JPA เพื่อค้นหาด้วยเงื่อนไขช่วงเวลา

สมมติว่ามีคลาสชื่อ Article ใช้เก็บบทความ ซึ่งมีฟิลด์ชื่อ publishingDate ระบุวันเวลาตีพิมพ์บทความ (อาจเป็นเวลาในอนาคตก็ได้)

public class Article {
    ...
    private OffsetDateTime publishingDate;
    ...
}
Enter fullscreen mode Exit fullscreen mode

และมีอินเทอร์เฟซ ArticleRepository extends CrudRepository<Article, Long> (สังเกตุว่าใช้ CrudRepository ก็พอ ไม่จำเป็นต้องใช้ JpaRepository)

เราสามารถเขียนเมธอดชื่อ findBy... เช่น findByAuthor(String author) เพื่อให้ได้ implementation ค้นหาด้วยชื่อผู้เขียนโดยอัตโนมัติ

แล้วหากต้องการเขียนชื่อเมธอดเพื่อค้นหา Article ที่มี publishingDate ระหว่างสองเวลาเช่น fromDate กับ toDate จะเขียนอย่างไร

วิธีเขียนที่ดูกระชับที่สุดคือ

List<Article> findByPublishingDateBetween(OffsetDateTime fromDate, OffsetDateTime toDate);
Enter fullscreen mode Exit fullscreen mode

ซึ่งวิธีนี้จะได้ผลลัพธ์แบบ inclusive คือนับรวมไปถึงจุดเวลาของ fromDate และ toDate ด้วย

ฉะนั้นหากต้องการค้น publishingDate ของวันนี้ทั้งหมด ทำได้ดังนี้

OffsetDateTime today = OffsetDateTime.now().with(LocalTime.MIN);
OffsetDateTime todayMaxTime = OffsetDateTime.now().with(LocalTime.MAX);
repository.findByPublishingDateBetween(today, todayMaxTime)
Enter fullscreen mode Exit fullscreen mode

ถ้าคุณมีข้อสงสัยหรืออยากแสดงความคิดเห็น ร่วมพูดคุยในคอมเมนต์ด้านล่างได้เลยครับ

Top comments (0)