Question

I've got a probably embarrassingly easy question regarding Hibernate:

When I've got a persisted instance of an object, and some of these object's properties are modified inside the same Session, are those changes visible for me too?

Or do I have to refresh the object in order to get it's current state?


I'd like to extend my question: What if these changes are not made inside the same Session? What if they are made in a Session, provided by the same SessionFactory?

Was it helpful?

Solution

If you have an entity loaded two or more times (doesn't matter if with Query.list() or Session.load()) then always you get the same instance of the Java object. And as it is the same instance, each modification of this instance is visible wherever you use this instance, and so this also is the case for modifications which are not persisted to the database (which is a certain danger).

If the entity is loaded two times using two different sessions (it doesn't matter if the sessions are from the same SessionFactory or not), then you get two instances of the Java class. These two instances are independent. One instance does not get informed about modifications in the other instance. This also is not the case if the modification is persisted into the database. Even if you load again the entity and it is already in the session cache, you do not get the modification (Example: session1.load(entity); session2.save(entity); session1.load(entity); then session1 does not load the changes which session2did, because the entity already was in the cache). The same is the case if a modification is done directly with SQL outside your program. To load the modification you either have to evict() the instance or use a new session. In this case it is recommendable to have a versioned column (a column mapped with the <version> clause) to avoid losses of modifications.

OTHER TIPS

No refresh needed, it will be visible unless it is detached.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top