2

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

1
  • Stupid me, the only wrong thing was that the propertyX was already set to "test". In that situation hibernate won't do anything. Setting it to "test2" after load and the committing, will result in a update. Commented Sep 29, 2011 at 9:23

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.