开发者

Why does loading an object with session.get doesn't persist object modifications at the end of session?

Maybe I misunderstood the semantics of get and merge in hibernate, but if I do this (in a Spring method controller, so using service and dao layers):

ClassMy a = se开发者_如何学Pythonrvice.get(234, ClassMy.class) (this loads the object using session.get)

a.setPropertyX("test");

this will not result in a automatic update. Instead, if I already had "a" in memory I would do:

a = (ClassMy) service.merge(a);
a.setPropertyX("test");

this results in a update.

Do I have to merge the object after loading it with get? Sounds so strange...


You have something wrong.

The first snippet should work, provided it's executed in the same transaction as the service.get call (i.e. the transaction should be started by the method containing this snippet, and not by the service.get method).

In the second snippet, if it runs in a transaction, then it should work: it loads the entity from the session, then copy the state of the detached a to the attached entity, then modifies the property of the attched entity. If it doesn't run in a transaction, (i.e. if it's service.merge which starts the transaction), the merge will work, but the change of the property will be done on a detached entity, and the new value of the property won't be persisted.


You have to make sure a transaction is there. Starting a transaction, call "Save" and then commit the transaction is mandatory.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜