tags:

views:

93

answers:

1

Why I need the line "session.save(user);" in the following code snippet? I thought, with the find call the user is already attached to the session and changes will be tracked and commited. Would you mind to explain the details for me? Or do I need a special configuration or other circumstances where I could have heard about this 'feature'?

session = createSession();
ta = session.beginTransaction();
assertEquals(1, session.createCriteria(MyUser.class).list().size());
// find one user
MyUser user = session.createCriteria(MyUser.class).uniqueResult();
user.setName("Rocker!");
// ### HERE ###
// WHY this 'save' is necessary!!??
session.save(user);
ta.commit();

ta = session.beginTransaction();
assertEquals(1, session.createCriteria(MyUser.class).list().size());
MyUser user = session.createCriteria(MyUser.class).uniqueResult();
assertEquals("Rocker!", user.getName());
ta.commit();

UPDATE 1

The same question applies to

  1. session.save(user);
  2. user.setName("Rocker!");
  3. ta.commit();

UPDATE 2

The solution to the problem is: I am using guice / warp persist. And in some cases I was incorrectly bound a code block to a transaction via @Transactional: so the transaction was committed too early opened and hence the separate change was not included in the commit. Thanks guys! So, always make sure you know about your transaction scope in case you are using spring or guice...

+3  A: 

You are correct that hibernate should automatically detect changes to the state of persistent objects:

Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.

I would assume that criteria results aren't returned in persistent state (but I can't seem to find proof of this in the docs)

Try using an HQL query, for which the docs are clear:

Entity instances retrieved by a query are in a persistent state

Also make sure that the flush mode of the session is set to AUTO or COMMIT.

Bozho
The flush mode 'AUTO' - is that the default and how can I change it?
rocker
With HQL query it is the same: an explicit save (after something changed) is necessary.
rocker
@rocker, `session.setFlushMode(FlushMode.AUTO)`.
Péter Török
@Peter Török this is the default, right? @Bozho thanks. Without that knowing for sure, I wouldn't have investigated it into details! -> see my update 2
rocker
@rocker, yes it is the default (I was not sure about it but now I checked).
Péter Török