Spring Data JPA와 Spring Boot를 활용한 검색 기능 구현
Overview
Spring Data JPA와 Spring Boot를 사용하여 효율적인 검색 기능을 구현하는 것은 현대 애플리케이션 개발에서 중요한 요소 중 하나입니다. 이 기술을 사용하면 데이터베이스에서 정보를 쉽게 쿼리하고 검색할 수 있으며, 복잡한 SQL 쿼리를 작성하지 않고도 데이터를 효율적으로 처리할 수 있습니다. 이번 글에서는 Spring Data JPA와 Spring Boot를 통해 검색 기능을 어떻게 구현하는지 자세히 설명하겠습니다.
1. 프로젝트 설정
먼저 Spring Boot 프로젝트를 설정해야 합니다. Spring Initializr를 사용하면 간단하게 프로젝트를 생성할 수 있습니다. 다음은 프로젝트 생성 시 선택할 설정입니다:
- Project: Maven Project
- Language: Java
- Spring Boot: 최신 버전 선택
- Dependencies: Spring Web, Spring Data JPA, H2 Database (혹은 사용할 데이터베이스에 맞는 드라이버)
Gradle 또는 Maven 설정
Maven pom.xml
예시:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. Entity 클래스 생성
검색할 데이터를 표현하기 위해 Entity 클래스를 생성합니다. 예를 들어, Product
라는 상품 정보를 저장하는 클래스를 생성하겠습니다.
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private Double price;
// getters and setters
}
3. Repository 인터페이스 생성
Spring Data JPA는 Repository 패턴을 사용하여 데이터베이스 접근을 단순화합니다. ProductRepository
라는 인터페이스를 생성하여 기본 CRUD 작업을 수행할 수 있도록 합니다.
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findByNameContaining(String name);
}
위의 메서드는 name
필드에 대해 부분 검색을 가능하게 합니다. findByNameContaining
메서드는 입력된 문자열이 포함된 모든 상품을 검색합니다.
4. 서비스 클래스 생성
비즈니스 로직을 처리하기 위해 서비스 클래스를 작성합니다. 이 클래스는 Repository와 상호작용하여 데이터를 처리합니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ProductService {
private final ProductRepository productRepository;
@Autowired
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public List<Product> searchProducts(String name) {
return productRepository.findByNameContaining(name);
}
}
5. 컨트롤러 클래스 생성
이제 웹에서 검색 기능을 사용할 수 있도록 REST API를 제공하는 컨트롤러 클래스를 작성합니다.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService productService;
@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping("/search")
public List<Product> search(@RequestParam String name) {
return productService.searchProducts(name);
}
}
위의 API는 GET /api/products/search?name=검색어
형태로 호출할 수 있습니다.
6. 에러 처리
개발 중에 에러가 발생할 수 있습니다. 예를 들어, 데이터베이스 연결 문제나 쿼리 실행 시 오류가 발생할 수 있습니다. 이러한 에러를 처리하기 위해 @ControllerAdvice
를 사용하여 전역 에러 핸들러를 작성할 수 있습니다.
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
7. H2 데이터베이스 설정 (테스트용)
H2 데이터베이스를 사용하여 로컬에서 쉽게 테스트할 수 있습니다. application.properties
파일에 다음 설정을 추가합니다.
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
이제 H2 데이터베이스 콘솔을 통해 데이터베이스를 확인할 수 있습니다. http://localhost:8080/h2-console
에 접속하여 로그인하면 됩니다.
8. 테스트
이제 애플리케이션을 실행하고 API를 호출하여 검색 기능을 테스트할 수 있습니다. Postman이나 cURL을 사용하여 다음과 같은 GET 요청을 보냅니다.
curl -X GET "http://localhost:8080/api/products/search?name=샘플"
위 요청을 통해 '샘플'이라는 이름이 포함된 모든 상품을 검색할 수 있습니다.
참고 문서
이처럼 Spring Data JPA와 Spring Boot를 활용하여 효율적인 검색 기능을 구현할 수 있습니다. 다양한 요구 사항에 맞추어 쿼리 메서드를 추가하거나 수정할 수 있으니, 필요에 따라 더 발전시켜 나가시면 좋습니다.
'Study Information Technology' 카테고리의 다른 글
스프링 부트 액츄에이터를 이용한 헬스 체크 엔드포인트 생성 (0) | 2024.10.15 |
---|---|
Spring Boot와 MongoDB를 이용한 NoSQL 애플리케이션 개발 (0) | 2024.10.14 |
Spring Boot와 RESTful 웹 서비스 현대 애플리케이션 개발의 핵심 (0) | 2024.10.14 |
Spring Boot와 Hibernate 통합 ORM의 힘을 활용하자 (0) | 2024.10.14 |
Spring Boot에서 멀티 모듈 프로젝트 생성하기 (0) | 2024.10.14 |