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 ;
@@ -33,9 +39,39 @@ public class DevInitData {
3339
3440 @ Bean
3541 ApplicationRunner DevInitDataApplicationRunner () {
36- return args -> {
37- initUsersAndPostsAndComments ();
38- };
42+ return args -> initialize ();
43+ }
44+
45+ @ Transactional
46+ public void initialize () {
47+ runDataSql ();
48+ initUsersAndPostsAndComments ();
49+ }
50+
51+ private void runDataSql () {
52+ try (Connection connection = dataSource .getConnection ()) {
53+ connection .setAutoCommit (true );
54+ Statement stmt = connection .createStatement ();
55+
56+ // post_category 테이블에 데이터 있는지 확인
57+ long count = postCategoryRepository .count ();
58+
59+ if (count == 0 ) {
60+ // 데이터가 없으면 data.sql 실행
61+ ResourceDatabasePopulator populator = new ResourceDatabasePopulator ();
62+ populator .addScript (new ClassPathResource ("data.sql" ));
63+ populator .setContinueOnError (true );
64+ populator .setIgnoreFailedDrops (true );
65+ populator .execute (dataSource );
66+
67+ System .out .println ("✅ data.sql executed because table was empty!" );
68+ } else {
69+ System .out .println ("ℹ️ Skipped data.sql (already has data: " + count + ")" );
70+ }
71+
72+ } catch (Exception e ) {
73+ System .err .println ("⚠️ data.sql execution failed: " + e .getMessage ());
74+ }
3975 }
4076
4177 @ Transactional
0 commit comments