开发者

Why I need to explicitely save after a find with Hibernate?

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...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜