H2 데이터베이스를 사용하면서 겪게 되는 문제들과 그에 대한 해결 방법들에 대해 알아봅시다. 먼저, 프로젝트에 H2 데이터베이스를 연동하는 방법을 살펴보겠습니다.
build.gradle 파일에 다음 코드를 추가합니다.
runtimeOnly 'com.h2database:h2'
application.properties 파일에 다음 코드를 추가합니다.
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:~/test # 경로는 사용자가 수정 가능
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect # 데이터베이스 엔진 종류 설정
spring.jpa.hibernate.ddl-auto=update # 엔티티를 기준으로 테이블을 생성하는 규칙을 정의
이제 /h2-console 경로로 들어가서 username과 password를 입력하고 접속하면 문제없이 접속이 가능합니다. 만약 일치하지 않는다는 오류가 발생하면 application.properties를 잘 정의했는지 확인해보세요.
application.properties 파일에서 다음 코드가 정의되어 있는지 확인해보세요.
spring.datasource.username=sa
spring.datasource.password=
username과 password를 입력하고 접속하면 문제없이 접속이 가능합니다. 한편, username과 password는 수정이 가능합니다.
오류 코드
"Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]] with root cause"
DB에 접속해 테이블을 확인해 본 결과, Entity 테이블이 생성되지 않는 문제가 발생했습니다. 이 경우, application.properties 파일에 다음 코드가 존재하는지 확인해보세요.
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
오류 코드
GenerationTarget encountered exception accepting command : Error executing DDL "create table user (id bigint not null, password varchar(255), username varchar(255), primary key (id))" via JDBC Statement
UserEntity.java
@Entity
@Getter
@ToString
@AllArgsConstructor
public class User {
@Id
@GeneratedValue
private Long id;
@Column
private String username
@Column
private String password;
}
위와 같이 코드를 구성하는 경우, 문제가 발생했습니다. 왜냐하면, 이 오류는 'user'라는 이름의 테이블을 생성하는 과정에서 문제가 발생했기 때문입니다. 즉, 'user'는 H2 데이터베이스에서 예약어이기 때문입니다. 이를 해결하기 위해 예약어를 사용하는 테이블 이름 대신 다른 이름을 사용해야 합니다.
수정 후
@Entity(name = "users")
@Getter
@ToString
@AllArgsConstructor
public class User {
@Id
@GeneratedValue
private Long id;
@Column
private String username;
@Column
private String password;
}
다음과 같이 이름을 예약어와 겹치지 않는 이름으로 설정해주는 경우 해결됩니다.
이상으로 H2 데이터베이스 연동 및 주요 오류 해결 방법에 대해 알아보았습니다. 프로젝트 진행 시 H2 데이터베이스에서 이와 관련된 문제가 발생한 경우 다음과 같이 해결해보세요.