-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* feat: 테스트 코드 격리 * fix: 중복 gradle 수정 * fix: guava 의존성 해제 * fix: guava 원복 * fix: DatabaseCleaner Service -> Component * fix: unwrap 이슈로 해결 및 guava 의존성 해제
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package com.depromeet; | ||
|
||
import jakarta.persistence.EntityManager; | ||
import jakarta.persistence.PersistenceContext; | ||
import java.sql.Connection; | ||
import java.sql.SQLException; | ||
import java.sql.Statement; | ||
import java.util.List; | ||
import java.util.stream.Collectors; | ||
import org.hibernate.Session; | ||
import org.springframework.beans.factory.InitializingBean; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
public class DatabaseCleaner implements InitializingBean { | ||
|
||
@PersistenceContext private EntityManager entityManager; | ||
private List<String> tableNames; | ||
|
||
@Override | ||
public void afterPropertiesSet() { | ||
entityManager.unwrap(Session.class).doWork(this::extractTableNames); | ||
} | ||
|
||
private void extractTableNames(Connection conn) { | ||
tableNames = | ||
entityManager.getMetamodel().getEntities().stream() | ||
.map(e -> e.getName().replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase()) | ||
.collect(Collectors.toList()); | ||
} | ||
|
||
public void execute() { | ||
entityManager.unwrap(Session.class).doWork(this::cleanUpDatabase); | ||
} | ||
|
||
private void cleanUpDatabase(Connection conn) throws SQLException { | ||
Statement statement = conn.createStatement(); | ||
statement.executeUpdate("SET REFERENTIAL_INTEGRITY FALSE"); | ||
|
||
for (String tableName : tableNames) { | ||
statement.executeUpdate("TRUNCATE TABLE " + tableName); | ||
statement.executeUpdate( | ||
"ALTER TABLE " | ||
+ tableName | ||
+ " ALTER COLUMN " | ||
+ tableName | ||
+ "_id RESTART WITH 1"); | ||
} | ||
|
||
statement.executeUpdate("SET REFERENTIAL_INTEGRITY TRUE"); | ||
} | ||
} |