티스토리 뷰
SpringBoot 에 h2 를 연결해서 JPA를 사용하는 기초 방법을 작성해본다.
사내에는 보통 구축된 DB가 있기 때문에 DB가 정해지지 않은 테스트 시 빼고는 잘 사용할 일이 없었는데
스터디하다가 연결하게 되어 남겨본다.
프로젝트 생성

IntelliJ 2023.3.4 를 사용하니까 이제 spring 프로젝트가 3버전으로 생성되어 jdk8 버전 프로젝트를 자동 생성할 수 없는 것 같다.
바꾸고 싶다면 상위버전으로 생성뒤에 다운그레이드 해야 할 듯 싶다?
다음으로 넘어가서 디펜던시를 추가하자

간단하게 필요한 녀석들만 추가해주고 프로젝트를 생성하자
아래와 같이 build.gradle 이 생성될 것이다.
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.3'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
프로젝트 설정
프로젝트가 생성되었으면
application.yml 을 설정해준다.
spring:
datasource:
driver-class-name: org.h2.Driver
url: 'jdbc:h2:mem:test' # In-Memory Mode
# url: 'jdbc:h2:~/test' # Embedded Mode
username: test
password: test1234
h2:
console:
enabled: true
path: /h2-console
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: create
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect
format_sql: true
show_sql: true
server:
port: 8080
H2 는 인메모리 모드(휘발성) 와 임베디드 모드(비휘발성)로 설정 할 수있다.
데이터를 안남겨도 되는 상황이면 인메모리 모드로 테스트해도 무방하다 본다.
h2 모드에 따라 url 을 위와 같이 다르게 설정하면 되고
h2 콘솔을 사용할꺼면 true 선언 뒤 웹에서 열 수 있는 path 를 설정하면 된다.
그리고 JPA 에 연결하기 위한 h2 연동 설정을 작성 해준다.
그럼 이제 h2 와 JPA 를 사용하기 위한 설정은 끝났다.
Entity 작성
@Entity
@Table(name = "member")
@NoArgsConstructor
public class Member {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Integer id;
@Column(name = "NAME")
private String name;
@Builder
public Member(Integer id, String name) {
this.id = id;
this.name = name;
}
}
간단하게 엔티티 하나 작성해주고 프로젝트를 실행한다.
프로젝트 Run
Hibernate:
drop table if exists member cascade
Hibernate:
drop sequence if exists member_seq
Hibernate:
create sequence member_seq start with 1 increment by 50
Hibernate:
create table member (
id integer not null,
name varchar(255),
primary key (id)
)
springboot 프로젝트가 구동되면서 엔티티에 따른 db를 create 한다.
( 위에 JPA설정에 ddl-auto를 'create' 로 설정했기 때문이다. )
h2 콘솔 확인
localhost:8080/h2-console
브라우저에서 위 링크에 접속하면 h2 콘솔이 뜬다.

url 은 아마 최초에 embedded 모드로 잡혀있을 것인데
사용하시는 거에 따라 변경해주시고
설정한 username과 password 를 입력하고 접속하면 된다.


접속하면 아까 생성한 엔티티에 따라 h2 db 를 셋팅한 것을 확인 할 수 있다.
가볍게 테스트 용도로 사용하긴 매우 간편하고 빠르다.
무료DB 들이 많기 때문에 해당 제품들을 사용해도 되지만
간단한 스터디용으로 db 를 사용한다면 좋을 것 이다.
참고블로그
스프링 부트(Spring Boot) - 5분 안에 H2 Database와 JPA 연동해보기
1. H2 Database란? H2 DB는 자바 기반의 오픈소스 관계형 데이터베이스 관리 시스템(RDBMS)입니다. 보통 테스트 단계 또는 작은 규모의 프로젝트에서 사용되며, Gradle 또는 Maven에 의존성만 추가해 주면
congsong.tistory.com
'Java > SpringBoot&Spring' 카테고리의 다른 글
[thymeleaf] Expression Utility 로 데이터 백분율 row 추가하기. (0) | 2024.05.03 |
---|---|
[SpringBoot] 정적리소스 cache control 설정. (2) | 2024.03.29 |
[Spring] @Autowired 지양하고 생성자를 사용하자. (0) | 2024.02.16 |
[Java] Reflection을 이용하여 Map<> 동적 key값 처리하기 (0) | 2024.01.16 |
[Java] Optional의 ifPresent 활용하기 (1) | 2024.01.10 |