Java/Spring Boot

[Spring Boot] 데이터베이스 초기화

hh_lin 2022. 4. 17. 20:28

1. JPA를 사용한 데이터베이스 초기화

  • spring.jpa.hibernate.ddl-auto
    - update/create-drop/create로 설정 시 자동으로 스키마 생성
    - update (사용 권장)
      : 기존에 있는 스키마는 그대로 두고, 추가된 것만 변경 / 컬럼명 변경시 기존 컬럼 삭제되지 않음

    - create-drop
      : 처음에 생성되고, 어플리케이션 종료 시 스키마 삭제

    - create
      : 초반에 띄울 때, 삭제 후 재생성
  • spring.jpa.generate-ddl=true로 설정 해줘야 동작함
! 운영 환경일 경우
spring.jpa.hibernate.ddl-auto=validate

spring.jpa.generate-ddl=false

 

 

 

 

 

 

# Account Entity

@Entity
public class Account {

	@Id @GeneratedValue
	private Long id;

	private String username;

	private String password;
    
	//getter, setter, equals, hashcode 생략
}

 

-> spring.jpa.hibernate.ddl-auto=update, spring.jpa.generate-dll=true 설정 후 실행해보면

account 스키마 확인 가능

 

 

 

 

 

 

 

 

 

# spring.jpa.show-sql

: true로 설정 시 실행되는 sql 확인 가능

 

 

 

 

 

 

 

 

 

 

 

 

 

2. SQL 스크립트를 사용한 데이터베이스 초기화

  • schema.sql 또는 schema-${platform}.sql
  • data.sql 또는 data-${platform}.sql
  • ${platform} 값은 spring.datasource.platform 으로 설정 가능
    - spring.datasource.platform=postgresql

    - schema-postgresql.sql
  • schema.sql -> data.sql 순으로 호출됨

 

# schema.sql

 

schema.sql이 있는 경우

spring.jpa.hibernate.ddl-auto=validate, spring.jpa.generate-ddl=false여도 schema.sql로 스키마 생성됨

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81%EB%B6%80%ED%8A%B8/dashboard

 

스프링 부트 개념과 활용 - 인프런 | 강의

스프링 부트의 원리 및 여러 기능을 코딩을 통해 쉽게 이해하고 보다 적극적으로 사용할 수 있는 방법을 학습합니다., - 강의 소개 | 인프런...

www.inflearn.com