0Pricing
Spring Boot 4 Complete Guide · 강의

사용자 정의 Spring Data 저장소

사용자 정의 메서드와 쿼리 정의를 추가해 복잡한 데이터 작업을 수행할 수 있도록 Spring Data JPA 저장소를 확장합니다.

사용자 정의 Spring Data 저장소은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 @Query methods.
  • 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 @Query annotation for both JPQL/HQL and native SQL queries to define specific data retrieval.
  • We briefly touched upon JpaSpecificationExecutor for 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 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.

“사용자 정의 Spring Data 저장소”에서 뭘 배우나요?

사용자 정의 메서드와 쿼리 정의를 추가해 복잡한 데이터 작업을 수행할 수 있도록 Spring Data JPA 저장소를 확장합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“사용자 정의 Spring Data 저장소” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 사용자 정의 Spring Data 저장소
  2. NoSQL 데이터베이스 통합
  3. Spring Cache를 활용한 캐싱
  4. Flyway를 활용한 데이터베이스 마이그레이션
← Spring Boot 4 Complete Guide(으)로 돌아가기