본문 바로가기
Programming/Spring

스프링 프레임워크 기초: H2 DB 활용

by vita12321 2023. 8. 10.
728x90
반응형

스프링 프레임워크에서 데이터 관리는 필수적인 요소입니다. 이번 글에서는 스프링 프레임워크에서 H2 DB를 활용하는 방법에 대해 자세히 설명하겠습니다. 여기서 H2 DB 설정, 스프링 데이터 관리, H2 DB와의 연동 등에 대한 내용을 포함합니다.


1. H2 데이터베이스 소개

 

H2 데이터베이스는 자바 기반의 인메모리 데이터베이스로, 주로 개발 단계에서의 테스트 용도로 사용됩니다. 오픈 소스로 제공되며 라이센스 제약이 없습니다. H2 데이터베이스는 메모리 모드와 디스크 기반 모드를 지원하며, 다양한 SQL 기능과 JDBC 드라이버가 포함되어 있습니다.


2. 스프링 부트에 H2 데이터베이스 적용하기

 

먼저, 스프링 부트 프로젝트에 H2 데이터베이스와 스프링 데이터 JPA 적용해 보겠습니다.

 

2.1. 의존성 추가

 

  • Gradle 기반 프로젝트의 경우 build.gradle 파일에 다음과 같이 의존성을 추가합니다.
//groovy


dependencies {

    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

    implementation 'com.h2database:h2'

}

 

  • Maven 기반 프로젝트의 경우 pom.xml 파일에 다음과 같이 의존성을 추가합니다.
//xml


<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-data-jpa</artifactId>

    </dependency>

    <dependency>

        <groupId>com.h2database</groupId>

        <artifactId>h2</artifactId>

    </dependency>

</dependencies>

 

2.2. 데이터 소스 설정

 

다음은 `src/main/resources/` 디렉토리 내에 위치한 `application.yml` 파일 (또는 `application.properties` 파일) H2 데이터베이스에 대한 데이터 소스 설정을 추가합니다.

 

  • `application.yml` 파일을 사용하는 경우:
//yaml


spring:

  datasource:

    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

    username: sa

    password:

    driver-class-name: org.h2.Driver

  jpa:

     hibernate.ddl-auto: update

  h2:

    console:

      enabled: true

      path: /h2-console

 

  • `application.properties` 파일을 사용하는 경우:
//properties

spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE

spring.datasource.username=sa

spring.datasource.password=

spring.datasource.driver-class-name=org.h2.Driver

 

spring.jpa.hibernate.ddl-auto=update

 

spring.h2.console.enabled=true

spring.h2.console.path=/h2-console

3. H2 데이터베이스와 연동하기

 

이제 스프링 데이터 JPA H2 데이터베이스를 연동하여 사용해보겠습니다.

 

3.1. JPA Entity 생성하기

 

먼저, 데이터베이스 테이블을 표현하는 JPA 엔티티 클래스를 작성합니다.

@Entity

public class User {

 

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

 

    @Column(nullable = false)

    private String name;

 

    private String email;

 

    // 생성자, getter, setter 생략

}

 

3.2. Repository 인터페이스 작성

 

다음으로, 스프링 데이터 JPA 이용해 `User` 엔티티와 관련된 CRUD 작업을 처리할 레파지토리 인터페이스를 작성합니다.

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

 

public interface UserRepository extends JpaRepository<User, Long> {

}

 

3.3. H2 데이터베이스 연동 테스트

 

스프링 부트 프로젝트에 H2 데이터베이스를 연동하고 테스트 코드를 작성합니다.

@RunWith(SpringRunner.class)

@SpringBootTest

public class UserRepositoryTest {

 

    @Autowired

    private UserRepository userRepository;

 

    @Test

    public void testCreateUser() {

        User user = new User();

        user.setName("홍길동");

        user.setEmail("hong@example.com");

        userRepository.save(user);

 

        User foundUser = userRepository.findById(user.getId()).orElse(null);

 

        assertNotNull(foundUser);

        assertEquals(user.getName(), foundUser.getName());

    }

}

4. 결론

 

이상으로 H2 데이터베이스를 스프링 프레임워크에 연동하여 사용하는 방법에 대한 설명을 마칩니다. 스프링 부트 프로젝트에서 H2 데이터베이스를 사용하면 사용이 간편하고, 속도도 빠르기 때문에, 개발 단계에서의 테스트 용도로 활용하기 좋습니다. 이외에도 H2 데이터베이스는 경량화되어 있어 기존 애플리케이션에도 무리 없이 통합할 있습니다.

728x90
반응형