1515import org .springframework .context .annotation .Bean ;
1616import org .springframework .context .annotation .Configuration ;
1717import org .springframework .context .annotation .Profile ;
18- import org .springframework .core .env .Environment ;
18+ import org .springframework .core .io .ClassPathResource ;
19+ import org .springframework .jdbc .datasource .init .ResourceDatabasePopulator ;
1920import org .springframework .security .crypto .password .PasswordEncoder ;
2021import org .springframework .transaction .annotation .Transactional ;
2122
23+ import javax .sql .DataSource ;
24+ import java .sql .Connection ;
25+ import java .sql .ResultSet ;
26+ import java .sql .Statement ;
2227import java .util .List ;
2328
2429@ Configuration
2530@ Profile ("default" )
2631@ RequiredArgsConstructor
2732public class DevInitData {
33+ private final DataSource dataSource ;
2834 private final UserRepository userRepository ;
2935 private final PostRepository postRepository ;
3036 private final CommentRepository commentRepository ;
@@ -34,10 +40,39 @@ public class DevInitData {
3440 @ Bean
3541 ApplicationRunner DevInitDataApplicationRunner () {
3642 return args -> {
43+ runDataSql ();
3744 initUsersAndPostsAndComments ();
3845 };
3946 }
4047
48+ private void runDataSql () {
49+ try (Connection connection = dataSource .getConnection ();
50+ Statement stmt = connection .createStatement ()) {
51+
52+ // post_category 테이블에 데이터 있는지 확인
53+ ResultSet rs = stmt .executeQuery ("SELECT COUNT(*) FROM post_category" );
54+ rs .next ();
55+ long count = rs .getLong (1 );
56+
57+ if (count == 0 ) {
58+ // 데이터가 없으면 data.sql 실행
59+ ResourceDatabasePopulator populator = new ResourceDatabasePopulator ();
60+ populator .addScript (new ClassPathResource ("data.sql" ));
61+ populator .setContinueOnError (true );
62+ populator .setIgnoreFailedDrops (true );
63+ populator .execute (dataSource );
64+
65+ System .out .println ("✅ data.sql executed because table was empty!" );
66+ } else {
67+ System .out .println ("ℹ️ Skipped data.sql (table already has data: " + count + ")" );
68+ }
69+
70+ } catch (Exception e ) {
71+ System .err .println ("⚠️ data.sql execution failed: " + e .getMessage ());
72+ }
73+ }
74+
75+
4176 @ Transactional
4277 public void initUsersAndPostsAndComments () {
4378 if (userRepository .count () == 0 ) {
0 commit comments