8.3. Persistence by Reachability (Cascading)

Persistence by reachability is the idea that if a transient object A references another transient object B, then persisting A will also persist B.

Both Naked Objects and also JPA support this concept. The Naked Objects' support is through the PersistAlgorithm interface. This allows object store implementations to instruct the persistor as to how to traverse the object graph. For example, the default algorithm (used by the in-memory object store) is implemented in DefaultPersistAlgorithm. This queues objects for persisting bottom-up, referred to (child objects) first and the parent objects. The TopDownAlgorithm, on the other hand, works the other way. The ability to plug in different algorithms provides flexibility for different persistence technologies.

JPA Objects uses (a trivial subclass of) the DefaultPersistAlgorithm. This is sufficient because the JPA provider (Hibernate) itself will persist objects in the correct order.

If required, you can also set the CascadeType using the cascade attribute of @ManyToOne and @OneToOne annotations. This can be thought of as a generalization of the persistence-by-reachability idea, cascading not only persists of transient objects, but also of updates and of removals (deletions).

CascadeType can take the following values:

In a Naked Objects application these methods are called from JPA Objects, not from your domain objects. specicailly, in the implementations of PersistenceCommand (for example JpaCreateCommand). Even so, there may be occasions when these annotations will influence the normal behaviour to accomplish a specific objective.

Note

Over time a set of patterns may emerge to help define suitable CascadeType settings for various domain model relationships. If so, this guide will be updated to provide further guidance.