1

In production, we use SQL scripts (Postgres) to generate / update the schema. In my unit tests, I use configProperties.put("hibernate.hbm2ddl.auto", "create-drop"); in order to create the schema for my H2 database.

In order to isolate the unit tests better, I want to drop and recreate the database in between tests. I can wipe the H2 database with entityManager.createNativeQuery("DROP ALL OBJECTS").executeUpdate();, but how do I then get hibernate to re-create the schema?

Or is there an easy way to simply shut down H2 and create a new instance? I can create multiple instances by using "jdbc:h2:mem:"+UUID.randomUUID()+";MODE=DB2;" as my connection string, but I'm not sure how to shut down / destroy / clean up previous instances.

Matt
  • 3,303
  • 5
  • 31
  • 53
  • [Result 1](https://stackoverflow.com/questions/15870168/what-is-wiping-my-h2-database-every-time-i-run-a-unit-test/15870245) and [Result 2](https://stackoverflow.com/questions/14343893/how-do-i-reset-my-database-state-after-each-unit-test-without-making-the-whole-t) by googling your question title – XtremeBaumer Jan 23 '19 at 12:10
  • Yep I've seen those, but they both rely on Spring (transactions, contexts etc) which we're not using. And I can't just wrap my test in a transaction and roll back the transaction because the code I'm testing has its own transaction handling, which is ultimately what I'm testing – Matt Jan 23 '19 at 12:14
  • [Result 3](https://shekhargulati.com/2018/01/09/programmatically-generating-database-schema-with-hibernate-5/) and [Result 4](https://stackoverflow.com/questions/44737662/how-do-you-programmatically-generate-a-hibernate-jpa-schema). I have the feeling you didn't look thoroughly – XtremeBaumer Jan 23 '19 at 12:23
  • @XtremeBaumer I didn't know about the programmatic SchemaExport, that solved my problem. If you make it an answer I'll accept. – Matt Jan 23 '19 at 14:45
  • Was result 3 or 4? – XtremeBaumer Jan 23 '19 at 15:25
  • I saw in 3 and 4 that I could programatically create a SchemaExport, although the actual code in there didn't work for me, but I managed to google some other examples using those as a starting point and figure out how to get it working in my case – Matt Jan 23 '19 at 17:25

0 Answers0