مستودعات Spring Data مخصّصة
وسّع مستودعات Spring Data JPA باستخدام أساليب مخصّصة وتعريفات للاستعلامات لتنفيذ عمليات بيانات معقّدة.
مستودعات Spring Data مخصّصة درس مجاني في Spring Boot 4 Complete Guide على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Spring Boot 4 Complete Guide، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Spring Boot 4 Complete Guide 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Intro to Custom Repositories
Spring Data JPA is amazing for reducing boilerplate code, but sometimes you need very specific, complex data operations that aren't covered by simple method name derivations.
This is where custom repositories come in! They allow you to define and implement your own complex data access logic, extending Spring Data JPA's capabilities.
When to Use Custom Logic
When do you need to write custom repository logic? Here are some common scenarios:
- Complex Joins & Aggregations: When standard query methods can't express your join or aggregation needs.
- Batch Operations: Performing updates or deletions on multiple records that require specific logic.
- Stored Procedures: Interacting with database-specific stored procedures.
- Performance Tuning: Applying specific query hints or optimizations.
- Business-Specific Operations: Logic that combines several data access steps into one cohesive method.
Defining a Custom Interface
The first step is to define an interface for your custom methods. This interface will declare the methods that don't fit Spring Data JPA's conventions.
Think of it as a blueprint for your unique data operations.
package com.coddykit.repo;
public interface CustomUserRepository {
void activateUsersOlderThan(int age);
// Add more specific methods here
}Implementing Custom Logic
Next, create a class that implements your custom interface. This is where you'll write the actual code for your complex data operations.
You'll typically use EntityManager from JPA or JdbcTemplate for more direct SQL interaction.
package com.coddykit.repo.impl;
import com.coddykit.repo.CustomUserRepository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
public class CustomUserRepositoryImpl implements CustomUserRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional
public void activateUsersOlderThan(int age) {
System.out.println("Executing custom logic...");
entityManager.createQuery(
"UPDATE User u SET u.active = true WHERE u.age > :age")
.setParameter("age", age)
.executeUpdate();
}
}Integrating with Main Repository
To make your custom implementation available, your main Spring Data JPA repository interface needs to extend your custom interface.
Spring Data JPA will automatically detect and link the implementation class (it expects the implementation class name to be [CustomInterfaceName]Impl).
package com.coddykit.repo;
import com.coddykit.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long>, CustomUserRepository {
// Standard methods from JpaRepository
// Plus custom methods from CustomUserRepository
}Full Custom Repository Demo
Let's see a complete example demonstrating a custom repository in action. We'll define a User entity, a UserRepository that combines standard and custom methods, and a Spring Boot app to use it.
Try running this example:
package com.coddykit;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.transaction.Transactional;
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.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
// 1. User Entity
@Entity
class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
private boolean active;
public User() {}
public User(String name, int age, boolean active) {
this.name = name;
this.age = age;
this.active = active;
}
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 int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public boolean isActive() { return active; }
public void setActive(boolean active) { this.active = active; }
@Override
public String toString() {
return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", active=" + active + '}';
}
}
// 2. Custom Interface
interface CustomUserRepository {
void activateUsersOlderThan(int age);
}
// 3. Custom Implementation
class CustomUserRepositoryImpl implements CustomUserRepository {
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional
public void activateUsersOlderThan(int age) {
System.out.println("Activating users older than " + age + "...");
entityManager.createQuery(
"UPDATE User u SET u.active = true WHERE u.age > :age")
.setParameter("age", age)
.executeUpdate();
}
}
// 4. Main Repository extends JpaRepository and Custom Interface
@Repository
interface UserRepository extends JpaRepository<User, Long>, CustomUserRepository {
// Spring Data JPA methods
}
@SpringBootApplication
public class Main implements CommandLineRunner {
@Autowired
private UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Override
public void run(String... args) throws Exception {
// Save some users
userRepository.save(new User("Alice", 25, false));
userRepository.save(new User("Bob", 30, false));
userRepository.save(new User("Charlie", 35, false));
System.out.println("--- Initial Users ---");
userRepository.findAll().forEach(System.out::println);
// Use custom method
userRepository.activateUsersOlderThan(28);
System.out.println("--- Users After Custom Update ---");
userRepository.findAll().forEach(System.out::println);
}
}Using @Query for JPQL/HQL
For specific queries that aren't easily expressed by method names, you can use the @Query annotation. It allows you to write JPQL (Java Persistence Query Language) or HQL (Hibernate Query Language) directly on your repository methods.
You can use positional parameters (?1) or named parameters (:paramName).
package com.coddykit.repo;
import com.coddykit.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.age > ?1 AND u.active = true")
List<User> findActiveUsersOlderThan(int age);
@Query("SELECT u FROM User u WHERE u.name LIKE %:namePart%")
List<User> findUsersWithNameContaining(@org.springframework.data.repository.query.Param("namePart") String namePart);
}Native SQL Queries with @Query
Sometimes, JPQL isn't enough, and you need to use native SQL queries specific to your database (e.g., for database-specific functions or performance reasons).
You can do this by setting nativeQuery = true in the @Query annotation. Be careful, as native queries are less portable across different databases.
package com.coddykit.repo;
import com.coddykit.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM User WHERE age < ?1 ORDER BY name", nativeQuery = true)
List<User> findYoungerUsersNative(int age);
@Query(value = "SELECT COUNT(*) FROM User WHERE active = :status", nativeQuery = true)
long countUsersByActiveStatusNative(@org.springframework.data.repository.query.Param("status") boolean status);
}Dynamic Queries with Specifications
For highly dynamic queries based on varying criteria (e.g., complex search filters), Spring Data JPA offers JpaSpecificationExecutor.
- It allows you to define reusable query predicates using the JPA Criteria API.
- This approach is powerful for building queries that change at runtime without needing to write many static
@Querymethods. - It's a more advanced technique for flexible search screens.
Custom Repository Check
Which of the following are valid ways to extend Spring Data JPA repositories with custom functionality?
Recap: Custom Repositories
In this lesson, we explored how to go beyond basic Spring Data JPA methods:
- We defined custom interfaces and implemented them to encapsulate complex, unique data access logic.
- We integrated these custom implementations with our main repositories.
- We learned to use the
@Queryannotation for both JPQL/HQL and native SQL queries to define specific data retrieval. - We briefly touched upon
JpaSpecificationExecutorfor building dynamic queries based on varying criteria.
These techniques empower you to handle almost any data access requirement in your Spring Boot applications!
الأسئلة الشائعة
هل درس «مستودعات Spring Data مخصّصة» مجاني؟
نعم — نص درس «مستودعات Spring Data مخصّصة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Spring Boot 4 Complete Guide، انتقل إلى CoddyKit PRO. تتضمن دورة Spring Boot 4 Complete Guide 4 دروس في المجموع.
ماذا ستتعلم في «مستودعات Spring Data مخصّصة»؟
وسّع مستودعات Spring Data JPA باستخدام أساليب مخصّصة وتعريفات للاستعلامات لتنفيذ عمليات بيانات معقّدة. تتمرن على Spring Boot 4 Complete Guide مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Spring Boot 4 Complete Guide؟
لا تُشترط خبرة سابقة. Spring Boot 4 Complete Guide على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «مستودعات Spring Data مخصّصة»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Spring Boot 4 Complete Guide هذا؟
نعم. كل درس في Spring Boot 4 Complete Guide يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- مستودعات Spring Data مخصّصة
- دمج قواعد بيانات NoSQL
- التخزين المؤقت باستخدام Spring Cache
- ترحيل قواعد البيانات باستخدام Flyway