Spring_15_Spring Boot 서버 실행 시 SQL 자동 실행

OngTK·2025년 10월 13일

Spring

목록 보기
15/25

📘 1. 기능 개요

Spring Boot는 application.properties 또는 application.yml 설정을 통해 서버 실행 시점에 SQL 파일을 자동 실행할 수 있음.

  • schema.sql → 테이블 생성/삭제 등 DDL 문 실행
  • data.sql → 데이터 삽입 등 DML 문 실행

주로 개발 및 테스트 단계에서 데이터베이스를 매번 초기화할 때 사용.
운영 환경에서는 대부분 비활성화(never) 함.


⚙️ 2. 설정 항목 요약

설정 키설명예시
spring.sql.init.modeSQL 자동 실행 여부 지정always, never
spring.sql.init.schema-locationsschema.sql 파일 경로 지정classpath:/sql/schema.sql
spring.sql.init.data-locationsdata.sql 파일 경로 지정classpath:/sql/data.sql
spring.datasource.initialization-mode(Spring Boot 2.5 이전) 동일 기능deprecated
spring.sql.init.encodingSQL 파일 인코딩 지정 (기본 UTF-8)UTF-8

🧩 3. application.properties 예시

## [4] 서버 실행 시, SQL 파일 실행
# 개발 단계에서만 사용하는 것이 일반적

# [4-1] SQL 실행 모드
# always : 항상 실행
# never  : 실행 안 함
spring.sql.init.mode=always

# [4-2] SQL 파일 경로 설정
# schema.sql : 테이블 구조 정의 (DDL)
# data.sql   : 초기 데이터 삽입 (DML)

# classpath = src/main/resources (기본 위치)
spring.sql.init.schema-locations=classpath:/sql/schema.sql
spring.sql.init.data-locations=classpath:/sql/data.sql

# [참고] 실행 순서
# 1. schema.sql 실행
# 2. data.sql 실행

🏗️ 4. schema.sql 작성 예시 (DDL)

테이블 생성 전 Drop table 추가 권장
외래키(FK)가 있는 경우 참조 순서에 유의

-- src/main/resources/sql/schema.sql
DROP TABLE IF EXISTS member;
CREATE TABLE member (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100),
    email VARCHAR(100)
);

DROP TABLE IF EXISTS book;
CREATE TABLE book (
    id INT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(100),
    author VARCHAR(100)
);

💾 5. data.sql 작성 예시 (DML)

테이블 초기 데이터 삽입용

-- src/main/resources/sql/data.sql
INSERT INTO member (name, email)
VALUES ('홍길동', 'hong@test.com'),
       ('김철수', 'kim@test.com');

INSERT INTO book (title, author)
VALUES ('Java 기초', '이순신'),
       ('Spring Boot 입문', '안중근');

⚠️ 6. 주의사항

  1. DB 생성은 불가

    • Spring SQL 초기화는 테이블만 생성/삭제 가능.
    • DB 생성(CREATE DATABASE)은 SQL 툴 또는 코드로 직접 수행.
  2. DDL 실행 시 FK 제약 주의

    • FK(외래키)가 있으면 Drop 시 참조 순서 필요.
  3. 운영 환경에서는 비활성화

    • 잘못된 설정 시 운영 데이터가 삭제될 수 있음.
    • 운영에서는 spring.sql.init.mode=never.
  4. 경로 오타 주의 (-locations)

    • spring.sql.init.schema-locations
    • spring.sql.init.data-locations
      (_ 대신 - 사용)

🧠 7. 동작 순서 요약

  1. 서버 시작 (SpringApplication.run())
  2. spring.sql.init.mode=always 확인
  3. schema.sql 실행 → DDL 처리
  4. data.sql 실행 → DML 처리
  5. DB 초기화 완료 후 ApplicationContext 로드 완료

🧩 8. 관련 예시 (AppStart.java)

@SpringBootApplication
public class AppStart {
    public static void main(String[] args) {
        SpringApplication.run(AppStart.class, args);
        System.out.println("🚀 서버 시작 완료!");
    }
}

위 설정이 존재할 경우, 서버 시작 시 자동으로 /resources/sql/schema.sql/resources/sql/data.sql 순으로 실행됨.


✅ 9. 정리

환경설정설명
개발spring.sql.init.mode=always서버 실행마다 DB 초기화
테스트spring.sql.init.mode=always통합 테스트 전 데이터 준비
운영spring.sql.init.mode=never데이터 보존, SQL 실행 비활성화

⚡ 결론
Spring Boot의 spring.sql.init.* 설정은 개발 단계에서 DB 자동 초기화를 위한 강력한 도구.
단, 운영 환경에서는 반드시 비활성화해야 함.
SQL 파일은 resources/sql/ 내에 두고, DDL → DML 순으로 실행됨.

profile
2025.05.~K디지털_풀스택 수업 수강중

0개의 댓글