How to change your Hibernate car conservation strategy

I just noticed that Hibernate objects are automatically stored in the database (or at least in the cache) before I call any methods save()or update(). For me, this is a rather weird default behavior - but it's fine, if I can disable it, that's fine.

The problem is that I want to update the state of my object (from state "1" to state "2") only if the entity in the database still has the state that it had when it was restored (state "1" "). This fixes concurrency problems when another server updates the same object. For this reason, I created a custom NamedQueryone that will only update the object if it is in the expected state" 1. "Here are a few pseudo codes:

// Get the entity
Entity item = dao.getEntity(); 
item.getState(); // == 1

// Update the entity
item.setState(2); // Here is the problem, this effectively changes the
                  // state of my entity breaking my query that verifies
                  // that state is still == 1.

dao.customUpdate(item); //Returns 0 rows changes since state != 1.

How to make sure that setters do not change state in / db cache?

+3
source share
2 answers

Hibernate , - ​​ . , hibernate . - , - .

. Concurrency

EDIT: , , , . , , db/cache. , . / , , . / ( ), , .

. Session.evict()

+1

. , # flush();

db, :

Bean bean = session.get(Bean.class, bean.getId());
session.setFlushMode(FlushMode.COMMIT);
// Make some changes to bean object.
Bean bean2 = session.get(Bean.class, bean.getId());
Assert.assertFalse(bean.equals(bean1)); // Assuming equals and hashcode are implemented
0

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


All Articles