sqlunit-testingjunith2h2db

How to delete rows from H2 table with commited changes after each Junit test


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?


Solution

  • 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.