Skip to content

Instantly share code, notes, and snippets.

@gunkim
Last active November 13, 2022 16:31
Show Gist options
  • Save gunkim/95b033e689b1d257f7dca4e5a33bd187 to your computer and use it in GitHub Desktop.
Save gunkim/95b033e689b1d257f7dca4e5a33bd187 to your computer and use it in GitHub Desktop.
데이터베이스를 포함한 테스트 시 테스트 격리를 위한 데이터베이스 초기화 코드
import com.google.common.base.CaseFormat;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
import static java.util.stream.Collectors.toList;
@Component
public class DatabaseClean implements InitializingBean {
@PersistenceContext
private EntityManager entityManager;
private List<String> tableNames;
@Override
public void afterPropertiesSet() {
tableNames = entityManager.getMetamodel().getEntities().stream()
.filter(e -> e.getJavaType().getAnnotation(Entity.class) != null)
.map(e -> CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, e.getName()))
.collect(toList());
}
@Transactional
public void execute() {
entityManager.flush();
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
for (String tableName : tableNames) {
entityManager.createNativeQuery(String.format("TRUNCATE TABLE %s", tableName)).executeUpdate();
entityManager.createNativeQuery(String.format("ALTER TABLE %s ALTER COLUMN ID RESTART WITH 1", tableName)).executeUpdate();
}
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment