2

I am using H2 in-memory DB for unit testing interaction with a database.

I need to clean commited changes in @After so that tables stay but all rows get wiped away (thus I cannot just drop tables). My database also has many foreign keys which makes even wiping objects one by one cumbersome as I have to do it in certain order.

Is there any way to clean rows in a database without dropping tables and preferably without deleting objects one by one?

Iwavenice
  • 556
  • 5
  • 22
  • 2
    Would a combination of [truncate](http://h2database.com/html/grammar.html#truncate_table) and temporarily [disabling referential integrity](http://www.h2database.com/html/grammar.html#set_referential_integrity) do the trick? – avandeursen Jan 09 '16 at 15:04
  • @Avandeursen Oh yes it does, thank you! And I think that I can batch truncate the tables too. What I needed is disabling referential integrity. – Iwavenice Jan 10 '16 at 17:52
  • Another option might be to use @DirtiesContext with "after each test" – John B Jan 11 '16 at 14:57
  • Glad it worked @AlexandraCohen. I have turned my comment into a real answer: Feel free to accept it if it worked for you. – avandeursen Jan 11 '16 at 18:14

1 Answers1

1

To clean the rows, you can use the H2 TRUNCATE TABLE data definition command.

You can temporarily disable checking foreign key constraints by using H2's SET REFERENTIAL_INTEGRITY.

avandeursen
  • 8,458
  • 3
  • 41
  • 51