Spring Data JDBC

2024. 5. 16. 09:40Back-End/Spring

Spring Data JDBC는 Spring 생태계에서 JDBC를 더 쉽고 편리하게 사용할 수 있도록 도와주는 데이터 접근 기술이다.

여기서는 Spring Data JDBC의 기본 개념과 사용법, 그리고 간단한 애플리케이션 예제를 통해 그 기능을 살펴보겠다.

 

Spring Data JDBC란?

Spring Data JDBC는 관계형 데이터베이스와 상호작용하는 간단하고 직관적인 방법을 제공한다. ORM(Object-Relational Mapping) 프레임워크와 달리, Spring Data JDBC는 SQL과의 직접적인 상호작용을 중시하여 더 예측 가능하고 간단한 데이터 접근 방식을 제공한다.

 

주요 개념

1. Repository 인터페이스

Spring Data JDBC에서 데이터 접근의 핵심은 Repository 인터페이스이다. 이 인터페이스는 기본적인 CRUD(Create, Read, Update, Delete) 작업을 위한 메서드를 제공한다.

public interface PersonRepository extends CrudRepository<Person, Long> { }

 

2. 엔티티 클래스

엔티티 클래스는 데이터베이스 테이블과 매핑된다. 이 클래스는 일반적으로 @Table 및 @Id 어노테이션으로 정의된다.

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

@Table("person")
public class Person {
    @Id
    private Long id;
    private String name;
    private int age;

    // Getters and setters
}

 

3. Query 메서드

Spring Data JDBC는 메서드 이름을 기반으로 쿼리를 자동으로 생성하는 기능을 제공한다.

List<Person> findByName(String name);

 

간단한 애플리케이션 예제

1. 프로젝트 설정

Spring Boot와 Spring Data JDBC를 사용하기 위해서는 spring-boot-starter-data-jdbc 의존성을 추가해야 한다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

 

2. 데이터 소스 설정

application.yml 파일에 데이터베이스 연결 설정을 추가한다.

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testdb
    username: root
    password: yourpassword
    driver-class-name: com.mysql.cj.jdbc.Driver

 

3. 엔티티 클래스 및 리포지토리 정의

import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;

@Table("person")
public class Person {
    @Id
    private Long id;
    private String name;
    private int age;

    // Getters and setters
}
import org.springframework.data.repository.CrudRepository;
import java.util.List;

public interface PersonRepository extends CrudRepository<Person, Long> {
    List<Person> findByName(String name);
}

 

4. 서비스 및 컨트롤러 구현

import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class PersonService {

    private final PersonRepository personRepository;

    public PersonService(PersonRepository personRepository) {
        this.personRepository = personRepository;
    }

    public List<Person> getAllPersons() {
        return (List<Person>) personRepository.findAll();
    }

    public Person getPersonById(Long id) {
        return personRepository.findById(id).orElse(null);
    }

    public Person savePerson(Person person) {
        return personRepository.save(person);
    }

    public void deletePerson(Long id) {
        personRepository.deleteById(id);
    }
}
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/persons")
public class PersonController {

    private final PersonService personService;

    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @GetMapping
    public List<Person> getAllPersons() {
        return personService.getAllPersons();
    }

    @GetMapping("/{id}")
    public Person getPersonById(@PathVariable Long id) {
        return personService.getPersonById(id);
    }

    @PostMapping
    public Person createPerson(@RequestBody Person person) {
        return personService.savePerson(person);
    }

    @DeleteMapping("/{id}")
    public void deletePerson(@PathVariable Long id) {
        personService.deletePerson(id);
    }
}

 

5. MainApplication 클래스와 CommandLineRunner

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }

    @Bean
    CommandLineRunner runner(PersonRepository repository) {
        return args -> {
            // 데이터 초기화
            repository.save(new Person(null, "John Doe", 30));
            repository.save(new Person(null, "Jane Smith", 25));

            // 모든 데이터 조회
            System.out.println("All persons:");
            repository.findAll().forEach(System.out::println);

            // 이름으로 조회
            System.out.println("Find by name 'John Doe':");
            repository.findByName("John Doe").forEach(System.out::println);
        };
    }
}

 

결론

Spring Data JDBC 간단한 데이터 접근 요구 사항을 가진 애플리케이션에 매우 유용한 도구이다. 관계형 데이터베이스와의 상호작용을 쉽게 만들어 주며, 이를 통해 가볍고 효율적인 데이터 접근 계층을 구현할 있다. CommandLineRunner 활용하여 애플리케이션 실행 초기 데이터를 설정하는 방법도 매우 유용할 것이다.

'Back-End > Spring' 카테고리의 다른 글

ResultSetExtractor  (0) 2024.05.17
@Transactional과 TransactionTemplate  (0) 2024.05.17
배치 업데이트(Batch Update)  (0) 2024.05.17
@Configuration 및 @Bean vs @ComponentScan  (0) 2024.05.14
IoC와 DI  (0) 2024.05.14