Skip to content

Commit af3a704

Browse files
committed
Ref: 데이터 중복 삽입 방지
1 parent e48bd3a commit af3a704

File tree

2 files changed

+41
-5
lines changed

2 files changed

+41
-5
lines changed

src/main/java/com/back/global/initData/DevInitData.java

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,22 @@
1515
import org.springframework.context.annotation.Bean;
1616
import org.springframework.context.annotation.Configuration;
1717
import 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;
1920
import org.springframework.security.crypto.password.PasswordEncoder;
2021
import 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;
2227
import java.util.List;
2328

2429
@Configuration
2530
@Profile("default")
2631
@RequiredArgsConstructor
2732
public 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

src/main/resources/application.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ spring:
3030

3131
sql:
3232
init:
33-
mode: always
33+
mode: never
3434

3535
security:
3636
oauth2:

0 commit comments

Comments
 (0)