An easy way to trim all tables, clear the sleep cache of the first and second level sleep mode?

I am writing some integration tests for the Spring / Hibernate application that I am working on, and I would like to test everything as close as possible to the real conditions, including using the Hibernate second level cache and completing the transaction.

I was wondering if there was an effective way to ask Hibernate to remove everything from the database and caches. The best I could come up with was to use the HQL "remove from XImpl" for each type of object, but I have dozens of domain objects, and it seems like there should be a better way.

+3
source share
3 answers

For the database, use the tool SchemaExportto recreate the schema:

Configuration cfg = ....;
new SchemaExport(cfg).create(false, true);

For the second level cache, get access to the main areas of the cache from SessionFactoryand evict everything:

SessionFactory sf = ...;
Cache cache = sf.getCache();
cache.evictEntityRegions();
cache.evictCollectionRegions();
cache.evictQueryRegions();

For level 1 cache, well, just get a new one Sessionor a challenge session.clear().

+5
source

Taking the Pascal approach above, I went looking for the right way to create a SchemaUpdate object in Spring and realized that I didn't need it. Instead, I can just get the Spring sessionFactory object for Hibernate and ask it to delete / create the schema. Combining this with the rest of Pascal's solution, we get the following:

LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean)appContext.getBean("&sessionFactory");
localSessionFactoryBean.dropDatabaseSchema();
localSessionFactoryBean.createDatabaseSchema();
Cache cache = sf.getCache();
cache.evictEntityRegions();
cache.evictCollectionRegions();
cache.evictQueryRegions();

. , ( ) , " obj1", " obj2" . , .

+1

Unitils. ( DbUnit), . , , - .

Unitils (empty-db.xml), :

<?xml version='1.0' encoding='UTF-8'?>
<dataset>
  <obj1/>
  <obj2/>
</dataset>

,

@DataSet("empty-db.xml")

, .

- , , Hibernate. , . unit test, Hibernate, .

, , , , .

+1

Source: https://habr.com/ru/post/1751832/


All Articles