How do I delete all JPA entities?

2019-07-23 06:05发布

In my testing code I need to have a blank/empty database at each method. Is there code that would achieve that, to call in the @Before of the test?

2条回答
地球回转人心会变
2楼-- · 2019-07-23 06:42

Actually you always can use JPQL,

em
   .createQuery("DELETE FROM MyEntity m")
   .executeUpdate()
;

But note, there is no grants that entity cache would be cleaned also. But for unit-test purposes it is look like good solution.

查看更多
Fickle 薄情
3楼-- · 2019-07-23 06:58

In my testing code I need to have a blank/empty database at each method.

I would run the test methods insider a transaction (and rollback at the end of each method). That's the usual approach. I don't see the point of committing a transaction and writing data to the database if you DELETE them just after. Just don't commit.

An alternative (not exclusive) would be to use DbUnit to put your database in a known state before a test execution. When doing this, you usually don't need to clean it up.

Another option would be to use raw JDBC to drop the database if exists and then have JPA recreate the whole database. Will be pretty slow though.

查看更多
登录 后发表回答