ทั้ง CrudRepository และ JpaRepository เป็นอินเทอร์เฟซของ Spring Data Repository library Spring Data Repository ลด boilerplate code ด้วยการให้ predefined finders สำหรับเข้าถึง data layer สำหรับ persistence layers ต่างๆ
JpaRepository extends CrudRepository และ PagingAndSortingRepository มันสืบทอด finders จาก crud repository เช่น findOne, save, delete entity และให้เมธอดเพิ่มเติมเกี่ยวกับ JPA เช่น delete records แบบ batch, flush ข้อมูลโดยตรงไปยัง DB และเมธอดเกี่ยวกับ pagination และ sorting
เราต้อง extend repository นี้ในแอปพลิเคชันของเรา แล้วจึงสามารถเข้าถึงเมธอดทั้งหมดที่มีอยู่ใน repository เหล่านี้ เรายังสามารถเพิ่มเมธอดใหม่ด้วย named queries หรือ native queries ตาม business requirements ได้
ตารางเปรียบเทียบรายละเอียด
| ลำดับ | หัวข้อ | JpaRepository | CrudRepository |
|---|---|---|---|
| 1 | ลำดับชั้น (Hierarchy) | JPA extends CrudRepository และ PagingAndSortingRepository | CrudRepository เป็น base interface ทำหน้าที่เป็น marker interface |
| 2 | รองรับ Batch | มีเมธอดเพิ่มเติม เช่น deleteInBatch, flush | ให้เฉพาะ CRUD functions เช่น findOne, save, etc. |
| 3 | รองรับ Pagination | extends PagingAndSortingRepository มีเมธอดสำหรับ pagination และ sorting | ไม่มีเมธอดสำหรับ pagination และ sorting |
| 4 | กรณีการใช้งาน | JpaRepository ผูก repository กับ JPA persistence technology ควรหลีกเลี่ยงถ้าไม่จำเป็น | ควรใช้ CrudRepository หรือ PagingAndSortingRepository ขึ้นกับว่าต้องการ sorting/paging หรือไม่ |
ตัวอย่าง JpaRepository
@Repository
public interface BookDAO extends JpaRepository<Book, Integer> {
Book findByAuthor(@Param("id") Integer id);
}
ตัวอย่าง CrudRepository
@Repository
public interface BookDAO extends CrudRepository<Book, Integer> {
Book findById(@Param("id") Integer id);
}
สรุป
CrudRepository เป็นพื้นฐานเบาๆ สำหรับ CRUD operations พื้นฐาน JpaRepository เพิ่มคุณสมบัติ JPA-specific เช่น batch operations, pagination, sorting และ flush ตรงๆ ควรเลือก CrudRepository หรือ PagingAndSortingRepository เพื่อหลีกเลี่ยงการผูกมัดกับ JPA implementation โดยตรง (loose coupling)