カスタムSpring Dataリポジトリ
Spring Data JPAリポジトリを拡張し、複雑なデータ操作に対応するカスタムメソッドとクエリ定義を追加します。
「カスタムSpring Dataリポジトリ」はCoddyKit上の無料Spring Boot 4 Complete Guideレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これは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!
AI チューターと学ぶ Java — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 21
- レッスン
- 84
よくある質問
「カスタムSpring Dataリポジトリ」レッスンは無料ですか?
はい。「カスタムSpring Dataリポジトリ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Complete Guideコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Complete Guideコースには全4レッスンが含まれています。
「カスタムSpring Dataリポジトリ」で何を学びますか?
Spring Data JPAリポジトリを拡張し、複雑なデータ操作に対応するカスタムメソッドとクエリ定義を追加します。 ブラウザで直接実行するハンズオンコードでSpring Boot 4 Complete Guideを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Spring Boot 4 Complete Guideを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSpring Boot 4 Complete Guideは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「カスタムSpring Dataリポジトリ」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSpring Boot 4 Complete Guideレッスンでコードを書いて実行できますか?
はい。すべてのSpring Boot 4 Complete Guideレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- カスタムSpring Dataリポジトリ
- NoSQLデータベースの統合
- Spring Cacheによるキャッシュ
- Flywayによるデータベースマイグレーション