user13121042
user13121042

Reputation:

Quarkus Panache Hibernate: How to clear the cache, make entity world match the database state?

I am new to quarkus and seem to be having a issue with the caching of hibernate in a unit test. The test has the 'UserTransaction' injected. The test should check a database cleanup task.

This is what to I do:

  1. create an entity
  2. start an transaction
  3. save the entity follwing the "Active Record" pattern with 'persistAndFlush'
  4. commit the transaction
  5. try to fetch the entity from the database via 'find(id)' to ensure it has been saved
  6. run the cleanup task (the entity is deleted from the db)
  7. try to fetch the entity from the database via 'find(id)' again to ensure it has been deleted
    Document doc;
    UUID uuid;
    doc = new Document();
    uuid = UUID.randomUUID();
    doc.uuid = uuid;
    doc.doc = new byte[0];
    doc.createdAt = Instant.now();
    transaction.begin();
    doc.persistAndFlush();
    transaction.commit();
    doc = Document.findById(uuid);
    Assertions.assertNotNull(doc);
    TimeUnit.SECONDS.sleep(Long.parseLong(maxAge)+1);
    scheduler.cleanUp();
    doc = Document.findById(uuid);
    Assertions.assertNull(doc);

Step 7 fails, because the 'find(id)' returns the entity, although it is not in the db anymore.

This does NOT happen if I skip step 5! So it seems to be caching issue to me.

I tried to Inject 'Session', 'SessionFactory' and 'EntitiyManager' to gain access to the current Hibernate Session, but none if this succeded.

Maybe the whole approach lacks something I didn`t get? How to make the world of entities match the database in a setup like mine?

Any hints and ideas are welcome.

TIA

Upvotes: 3

Views: 2423

Answers (2)

张鹏鹏
张鹏鹏

Reputation: 11

There's cache in the same transaction. So The second find in the step 7 is just get value from cache. The session is bond to the transaction,so clear the session which you inject in is not working. You must get session from the panache, then run clear method before find method.I think start a new transaction is not essential about this problem.

Upvotes: 0

user13121042
user13121042

Reputation:

The problem has a simple solution, add a transaction to the last find operation:

transaction.begin();
doc = Document.findById(uuid);
transaction.commit();

Upvotes: 3

Related Questions