spring boot data 예제

Spring Boot Data는 Spring Boot 프레임워크를 사용하여 데이터베이스와 상호 작용하는 애플리케이션을 개발하는 데 도움이 되는 많은 기능과 유틸리티를 제공합니다. 이번 예제에서는 Spring Boot Data를 사용하여 데이터베이스에 접근하고 CRUD(Create, Read, Update, Delete) 작업을 수행하는 방법을 알아보겠습니다.

의존성 설정

먼저 Maven 또는 Gradle을 사용하여 프로젝트에 필요한 의존성을 설정해야 합니다. pom.xml 파일에서 Maven을 사용하는 경우, 다음과 같이 의존성을 추가할 수 있습니다.

<dependencies>
    <!-- Spring Boot Data JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

Gradle을 사용하는 경우, build.gradle 파일에 다음과 같이 의존성을 추가할 수 있습니다.

dependencies {
    // Spring Boot Data JPA
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
}

엔티티 생성

이제 데이터베이스와 연결하고 데이터를 저장할 엔티티를 생성해야 합니다. 예를 들어, User라는 엔티티를 생성해보겠습니다.

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private int age;

    // Getters and Setters
}

위의 코드에서 @Entity 어노테이션은 이 클래스가 JPA 엔티티임을 나타내고, @Id@GeneratedValue 어노테이션은 primary key로 사용될 필드인 id를 설정합니다.

Repository 작성

다음으로, 데이터베이스와 상호 작용을 위해 Repository를 작성해야 합니다. Repository는 데이터베이스의 CRUD 작업을 추상화한 인터페이스입니다.

import org.springframework.data.jpa.repositoru.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}

UserRepository 인터페이스는 JpaRepository를 상속받고, 제네릭으로 User 엔티티와 ID 타입을 지정합니다.

서비스 작성

이제 Repository에서 정의한 CRUD 메서드를 사용하는 서비스를 작성해야 합니다. 서비스는 비즈니스 로직을 처리하고 Repository를 통해 데이터베이스에 접근합니다.

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional
    public User createUser(User user) {
        return userRepository.save(user);
    }

    @Transactional(readOnly = true)
    public User getUser(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Transactional
    public User updateUser(User user) {
        return userRepository.save(user);
    }

    @Transactional
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

위의 코드에서 @Service 어노테이션은 이 클래스가 서비스임을 나타내고, @Transactional 어노테이션은 메서드에 트랜잭션 처리를 적용합니다.

컨트롤러 작성

마지막으로, 컨트롤러를 작성하여 REST API 엔드포인트를 제공합니다.

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
        User existingUser = userService.getUser(id);
        if (existingUser == null) {
            throw new NotFoundException("User not found");
        }
        user.setId(id);
        return userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}

위의 코드에서 @RestController 어노테이션은 이 클래스가 REST 컨트롤러임을 나타내고, @RequestMapping 어노테이션은 엔드포인트의 기본 URL을 설정합니다.

실행 및 테스트

이제 Spring Boot 애플리케이션을 실행하고 API를 테스트해볼 수 있습니다. 예를 들어, localhost:8080/users로 POST 요청을 보내면 새로운 사용자를 생성할 수 있습니다.

POST /users
Content-Type: application/json

{
    "name": "John Doe",
    "age": 25
}

위의 예시를 따라하면 사용자를 생성하고 데이터베이스에 저장할 수 있습니다. 이와 마찬가지로 GET, PUT, DELETE 요청을 사용하여 사용자를 조회, 수정, 삭제할 수 있습니다.

결론

이번 예제에서는 Spring Boot Data를 사용하여 데이터베이스와 상호 작용하는 방법을 알아보았습니다. Spring Boot Data의 다양한 기능과 유틸리티를 활용하면 간편하고 효율적인 데이터베이스 애플리케이션을 개발할 수 있습니다.