Niestandardowe repozytoria Spring Data
Proszę rozszerzać repozytoria Spring Data JPA o niestandardowe metody i definicje zapytań na potrzeby złożonych operacji na danych.
Niestandardowe repozytoria Spring Data to bezpłatna lekcja Spring Boot 4 Complete Guide na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Complete Guide, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Complete Guide zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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!
Ucz się Java dzięki korepetycjom AI — za darmo
Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.
- Kursy
- 21
- Lekcje
- 84
Często zadawane pytania
Czy lekcja „Niestandardowe repozytoria Spring Data” jest bezpłatna?
Tak — pełny tekst „Niestandardowe repozytoria Spring Data” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Complete Guide, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Complete Guide zawiera 4 lekcji w sumie.
Co nauczysz się w „Niestandardowe repozytoria Spring Data”?
Proszę rozszerzać repozytoria Spring Data JPA o niestandardowe metody i definicje zapytań na potrzeby złożonych operacji na danych. Ćwiczysz Spring Boot 4 Complete Guide z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Complete Guide?
Nie wymagamy żadnego doświadczenia. Spring Boot 4 Complete Guide w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.
Ile czasu zajmuje lekcja „Niestandardowe repozytoria Spring Data”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Complete Guide?
Tak. Każda lekcja Spring Boot 4 Complete Guide zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Niestandardowe repozytoria Spring Data
- Integracja z bazami danych NoSQL
- Buforowanie z użyciem Spring Cache
- Migracje baz danych za pomocą Flyway