IT 기술/[JAVA] Spring Boot
8-1. 프로젝트에서 JPA 직접 사용해보기
Lee Hye Won
2021. 5. 8. 10:34
지금까지 공부했던 것들을 직접 코딩하며 살펴본다.
우선 Spring 프로젝트의 생성은 Spring initializer 의 도움을 받았다. (URL : start.spring.io)
프로젝트를 열고 application.properties 의 설정 내용은 아래와 같다.
// application.properties
#H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.hikari.jdbc-url=jdbc:h2:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.initialization-mode=always
#JPA
spring.jpa.datasource-platform=org.hibernate.dialect.H2Dialect;
spring.jpa.hibernate.ddl-auto=validate
# hibernate 가 console 에 로깅해주는 정보들을 세팅
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.use_sql_comments=true
spring.jpa.properties.hibernate.format_sql=true
# spring.jpa.hibernate.ddl-auto=validate
→ JPA 와 DDL 을 사용할지에 대한 설정이다. validate는 JPA 가 DDL 을 건드리지 못하게 한다.
application.properties 를 build, 프로젝트를 실행한 후, http://localhost:8080/h2/login.do 에 접속하면 아래와 같은 화면이 나온다.
이제 schema.sql 파일을 생성 후 작성을 할건데,
H2 데이터베이스는 schema.sql 파일을 만들어주면, 데이터베이스가 실행될 때 (서버가 올라갈 때마다) 해당 파일에 있는 쿼리를 한 번 실행시켜준다.
서버가 올라갈 때마다 해당 쿼리가 실행되기 때문에 해당하는 테이블이 이미 존재하면 테이블을 DROP 시켜주는 소스도 추가한다.
// schema.sql
DROP TABLE IF EXISTS CAR;
CREATE TABLE CAR (
id bigint auto_inclement,
model_name varchar(255) not null,
company_id bigint not null,
passenger_capacity int,
created_at TIMESTAMP not null,
updated_at TIMESTAMP not null,
primary key(id)
);
DROP TABLE IF EXISTS COMPANY;
CREATE TABLE COMPANY(
id bigint auto_inclement,
company_name varchar(255) not null,
company_nation varchar(255) not null,
created_at TIMESTAMP not null,
updated_at TIMESTAMP not null,
primary key(id)
);
다시 실행해보면 CAR, COMPANY 테이블이 생성되어 있음을 확인할 수 있다.