Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DataInitializer에서 불필요한 커넥션 제거 #554

Merged
merged 1 commit into from
Oct 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 9 additions & 23 deletions server/src/test/java/com/project/yozmcafe/DataInitializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,10 @@
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -21,20 +17,18 @@ public class DataInitializer {

private static final int OFF = 0;
private static final int ON = 1;
private static final int FIRST_COLUMN = 1;
private static final String FLYWAY = "flyway";
private static final String TRUNCATE = "TRUNCATE ";

@Autowired
private DataSource dataSource;
@PersistenceContext
private EntityManager em;

private final List<String> deleteDMLs = new ArrayList<>();
private final List<String> truncationDMLs = new ArrayList<>();

@BeforeEach
@Transactional
public void deleteAll() {
if (deleteDMLs.isEmpty()) {
if (truncationDMLs.isEmpty()) {
init();
}

Expand All @@ -48,25 +42,17 @@ private void setForeignKeyEnabled(final int enabled) {
}

private void truncateAllTables() {
deleteDMLs.stream()
truncationDMLs.stream()
.map(em::createNativeQuery)
.forEach(Query::executeUpdate);
}

private void init() {
try (final Statement statement = dataSource.getConnection().createStatement()) {
final ResultSet resultSet = statement.executeQuery("SHOW TABLES ");
final List<String> tableNames = em.createNativeQuery("SHOW TABLES ").getResultList();

while (resultSet.next()) {
final String tableName = resultSet.getString(FIRST_COLUMN);
if (tableName.contains(FLYWAY)) {
continue;
}

deleteDMLs.add("TRUNCATE " + tableName);
}
} catch (Exception e) {
e.printStackTrace();
}
tableNames.stream()
.filter(name -> !name.contains(FLYWAY))
.map(TRUNCATE::concat)
.forEach(truncationDMLs::add);
}
}