tharindu_DG
tharindu_DG

Reputation: 9271

Hibernate Transaction Context with Struts2 Actions

I have a scenario where, a Struts2 action fetches a model object from back-end and puts it in to the OGNL stack and the front end view is updated with that data.

Then I change a value in the view that corresponds to the model object and update. Then that value is saved using Hibernate's getSession().update(model) method.

Question : When the model object is read in to the OGNL stack, that transaction context closes and the model object gets detached. Why am I allowed to save the change using getSession().update(model)? I think getSession().merge(model) should be used.

Please help me to understand the ambiguity.

Upvotes: 1

Views: 91

Answers (1)

Roman C
Roman C

Reputation: 1

Both methods can pass detached object as parameter, but if there's an object in the context with the given identifier, the first method throws an exception. Read

Update the persistent instance with the identifier of the given detached instance. If there is a persistent instance with the same identifier, an exception is thrown.

public void update(Object object);

The second method doesn't throw an exception because it loads not existing object by its identifier to the context, update it, and returns to the caller.

Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.

public Object merge(Object object);

Upvotes: 1

Related Questions