How do I delete all JPA entities?

元气小坏坏 提交于 2019-12-13 19:48:45

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/3333308/how-do-i-delete-all-jpa-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!