From 472b410ac7d5e1bfc08dcce61dcfbf86bd8d77f1 Mon Sep 17 00:00:00 2001 From: ysh Date: Thu, 7 Nov 2024 08:14:27 +0900 Subject: [PATCH] update properties And Add Database Initializer --- .../co/mcmp/config/DatabaseInitializer.java | 35 +++++++++++++++++++ src/main/resources/application.yaml | 4 +-- 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 src/main/java/kr/co/mcmp/config/DatabaseInitializer.java diff --git a/src/main/java/kr/co/mcmp/config/DatabaseInitializer.java b/src/main/java/kr/co/mcmp/config/DatabaseInitializer.java new file mode 100644 index 0000000..c38e78b --- /dev/null +++ b/src/main/java/kr/co/mcmp/config/DatabaseInitializer.java @@ -0,0 +1,35 @@ +package kr.co.mcmp.config; + +import java.nio.charset.StandardCharsets; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.core.io.Resource; +import org.springframework.core.io.ResourceLoader; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; + +@Component +public class DatabaseInitializer implements CommandLineRunner{ + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Autowired + private ResourceLoader resourceLoader; + + @Override + public void run(String... args) throws Exception { + if (isDatabaseEmpty()) { + Resource resource = resourceLoader.getResource("classpath:import.sql"); + String sql = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8); + jdbcTemplate.execute(sql); + } + } + + private boolean isDatabaseEmpty() { + Long count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM workflow", Long.class); + return count != null && count == 0; + } +} \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 38abd0f..556a898 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -10,7 +10,7 @@ spring: name: workflow-manager #h2 db 설정 datasource: - url: jdbc:h2:file:./document/workflow # 프로젝트 루트/db/ 안에 h2.db파일(test.mv.db) 생성 + url: jdbc:h2:file:./document/test/workflow # 프로젝트 루트/db/ 안에 h2.db파일(test.mv.db) 생성 driver-class-name: org.h2.Driver username: ${DB_ID:workflow} password: ${DB_PW:workflow!23} @@ -38,7 +38,7 @@ spring: sql: init: data-locations: classpath:import.sql - mode: ${SQL_DATA_INIT:always} # ${SQL_DATA_INIT:never} + mode: always # ${SQL_DATA_INIT:never} platform: h2 #schema-locations: classpath:ddl.sql