views:

998

answers:

2

Can some explain to me what is the advantage of using detached objects within the context of a web application? AFAIK they are only useful if the objects somehow outlive the "lexical" scope of the transaction, but typically in a web app when your transaction is over you just send your objects to the view layer, and they will not be reattached.

To the best of my understanding, detaching an object is only useful if you are going to merge/reattach it later, and I am failing to see the advantage of this in relation to just simply doing a straight update of the object to the DB.

Any sample code is appreciated.

Edit: for clarification, I'm trying to understand the advantages of a detached object vs. a transient (one that came for the db for example but cannot be later reattached).

A: 

Suppose you have a page with dozens of drop downs that are populated from rows in various tables. You don't want to have to make round trips to the DB every time you render the page, so you can grab the lists of objects, detach them and store them somewhere. As long as you take care to avoid referencing properties that might be lazy loaded you're fine.

Jherico
But this way my objects can be stale. Besides, I'm trying to understand what's the difference of using detach vs. transient.
Miguel Ping
+1  A: 

The detached object may also hold its version number (if you have a versioning column). If you take the approach for an entity editor, for instance, of loading the entity and stashing it in a http-session (or other longer-lived store), and then updating it and merging it back into a different session on a later interaction, then Hibernate can automatically check that the entity (or other entities in your merged object graph) has not been concurrently modified.

araqnid