Truncate All Tables in Spring Boot


Truncate All Tables(for Testing)

/// Delete Tables Component
@Component
class DataCleaner(
        private val dataSource: DataSource,
        private val entityManager: EntityManager
) {
  private var tables: List<String>? = null
  fun deleteAll() {
    dataSource.connection.use { con ->
      // Safety
      if (!con.metaData.url.contains("unittest")) {
          throw Exception("DANGER!!!")
      }
      if (tables == null) {
        tables = con.metaData.getTables(con.catalog, null, null, arrayOf("TABLE")).use {
          var ar = mutableListOf<String>()
          while (it.next()) {
            ar.add(it.getString("TABLE_NAME"))
          }
          ar
        }
      }
      con.createStatement().use { st ->
        st.execute("SET FOREIGN_KEY_CHECKS = 0")
      }
      tables?.map {
        con.createStatement().use { st ->
          st.execute("TRUNCATE TABLE `$it`")
        }
      }
      con.createStatement().use { st ->
        st.execute("SET FOREIGN_KEY_CHECKS = 1")
      }
    }
    entityManager.clear()
  }
}

/// Usage
class SomethingTest {
  @Autowired
  lateinit var dataCleaner: DataCleaner

  @BeforeEach
  fun initDB() {
      dataCleaner.deleteAll()
  }
  @Test
  fun testSomething() {
    ...
  }
}

See also