Database Reference
In-Depth Information
Listing 9.12. Active record persistence with implicit transaction
If you cast your eyes over the code in listing 9.12 , it more than likely will conjure up a few
questions, such as “Does this code even work?” The absence of any transaction code does
look a bit suspect, given that all operations need to occur within a transaction.
Remember,nodeentitiescanexistintwostates: attached or detached .Creatinganewnode
entityoccursinadetachedstate,whichsimplymeansthattheentityhasnotyethaditsstate
written into the underlying graph database.
Calling persist() on the entity (or indeed Neo4jTemplate's save() meth-
od) attaches the entity to the graph. Attachment ensures that the state in the entity is syn-
chronized with that in the graph database. For new entities, new nodes and properties are
created,andforentitiesthatwereatsomepointpreviouslyattached,they'rereattached,en-
suring any changes since the last attachment are written to the graph.
SDN can detect whether or not your code is operating within the context of an existing
transaction. If not (as is the case in the sample code), SDN will ensure that calls to the
attach-related methods( NodeBacked's persist inthiscase,aswellas Neo4jTem-
plate's save ) will create an implicit transaction for you. An implicit transaction is
simply a new transaction created for you internally
that SDN then uses to perform the
mutating calls that save the state into the graph.
Although we've provided details here about how implicit transaction works, you're gener-
ally advised to provide explicit transactions yourself. Otherwise the library has to reattach
detached entities all the time. Having tiny implicit transactions can also slow down your
application tremendously.
 
Search WWH ::




Custom Search