[Spring Boot] JPA 설정 및 사용 방법

KUKJIN LEE's profile picture

KUKJIN LEE3개월 전 작성

Spring Boot는 데이터베이스와의 상호작용을 간소화하고, 복잡한 설정 없이도 JPA(Java Persistence API)를 손쉽게 활용할 수 있도록 지원합니다.

 

객체와 관계형 데이터베이스 간의 매핑(ORM)을 통해, SQL 작성 없이도 데이터를 저장하고 조회할 수 있습니다.

 

Spring Boot에서 JPA 설정하기

Spring Boot는 JPA와 Hibernate를 기본적으로 지원하며, 간단한 설정으로 JPA를 활용할 수 있습니다.

 

필요한 Dependency 추가

Spring Boot 프로젝트에서 JPA를 사용하려면 spring-boot-starter-data-jpa 의존성을 추가해야 합니다.

<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>

 

application.properties 설정

JPA와 데이터베이스 연결을 위해 Spring Boot의 application.properties 또는 application.yml 파일에 설정을 추가해야 합니다.

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=admin
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

주요 설정 옵션

  • spring.datasource.url: 데이터베이스 연결 URL

  • spring.jpa.hibernate.ddl-auto: 데이터베이스 스키마 자동 생성(create, update, none 등)

  • spring.jpa.show-sql: 실행되는 SQL 로그를 출력 여부

  • spring.jpa.properties.hibernate.dialect: 사용하는 데이터베이스에 맞는 Hibernate 방언 설정

 

JPA 사용 예제

3.1 Entity 클래스 생성

데이터베이스 테이블과 매핑되는 Entity 클래스를 생성합니다.

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

@Entity
public class User {

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

    private String name;
    private String email;

    // Getter, Setter, toString 메서드
}

 

Repository 생성

데이터 조작을 위한 Repository 인터페이스를 생성합니다.

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

public interface UserRepository extends JpaRepository<User, Long> {
    // 커스텀 메서드 예: 이름으로 사용자 찾기
    User findByName(String name);
}

 

Service 및 Controller 작성

Service 클래스

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User saveUser(User user) {
        return userRepository.save(user);
    }
}

 

Controller 클래스

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> getUsers() {
        return userService.getAllUsers();
    }

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

 

JPA 실행 확인

Spring Boot 애플리케이션을 실행하고, Postman이나 cURL로 REST API를 호출하여 JPA 작동 여부를 확인합니다.

  • GET 요청: /users → 저장된 사용자 리스트 반환

  • POST 요청: /users → 새 사용자 저장

New Tech Posts