Skip to content

Commit 60a1811

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

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

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

Lines changed: 36 additions & 1 deletion
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;
@@ -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) {

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)