Skip to content

Instantly share code, notes, and snippets.

@JorgenRingen
Created October 18, 2018 10:31
Show Gist options
  • Save JorgenRingen/68186142012663f2ee547d187040a1b7 to your computer and use it in GitHub Desktop.
Save JorgenRingen/68186142012663f2ee547d187040a1b7 to your computer and use it in GitHub Desktop.
Empty @Entity-tables before running test
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Table;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Inspirert av: <a href="https://medium.com/@dSebastien/cleaning-up-database-tables-after-each-integration-test-method-with-spring-boot-2-and-kotlin-7279abcdd5cc">
* https://medium.com/@dSebastien/cleaning-up-database-tables-after-each-integration-test-method-with-spring-boot-2-and-kotlin-7279abcdd5cc
* </a>
* <p>
* Gjør manuell opprydding etter hver test, da automatisk rollback ikke er mulig med kombinasjonen @SpringBootTest og SpringBootTest.WebEnvironment.RANDOM_PORT.
* <blockquote>
* If your test is @Transactional, it rolls back the transaction at the end of each test method by default.
* However, as using this arrangement with either RANDOM_PORT or DEFINED_PORT implicitly provides a real servlet environment,
* the HTTP client and server run in separate threads and, thus, in separate transactions. Any transaction initiated on
* the server does not roll back in this case.
* <cite>
* <a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html">
* https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
* </a>
* </cite>
* </blockquote>
*/
@Service
@Profile("test")
public class DatabaseCleanup implements InitializingBean {
@PersistenceContext
private EntityManager entityManager;
private List<String> tableNames;
@Transactional
public void execute() {
entityManager.flush();
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
for (final String tableName : tableNames) {
entityManager.createNativeQuery("TRUNCATE TABLE " + tableName).executeUpdate();
}
entityManager.createNativeQuery("SET REFERENTIAL_INTEGRITY TRUE").executeUpdate();
}
@Override
public void afterPropertiesSet() throws Exception {
tableNames = entityManager.getMetamodel().getEntities().stream()
.filter(e -> e.getJavaType().getAnnotation(Table.class) != null)
.map(e -> e.getJavaType().getAnnotation(Table.class).name())
.collect(Collectors.toList());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment