How to cascade update

# How to cascade update

## Overview

When working with long transactions, you can cascade the db.update() operation, so that, for example, updating the root of a large object graph causes all connected entities to update as well (provided cascading update is enabled on the particular relationships, of course).

## Enabling cascading update

To enable cascading update on a relationship you simply set the cascading attribute of the `<sql>` field describing the relation to "`update`" (or "`all`"):

    <field name="book" type="myapp.Book" >
      <sql name="book_id" cascading="update" />
    </field>

In case of bidirectional relationships, be aware that it matters on which end you enable cascading update. It is also possible to enable it on both ends.

## Scenarios

### db.update()

Let's say we have the objects Author and Book and they are in a one-to-one relationship, with every Book having exactly one Author. The database looks like this:

Author

id | name
--- | ---
1 | "John Jackson"

Book

id | title | author_id
--- | --- | ---
1 | "My Life" | 1

Now let's change the book's title. Note that we never directly load the book and that the change happens outside of any transaction:

    db.begin();
    Author a1 = db.load(Author.class, 1);
    db.commit();

    a1.getBook().setName("My Fantastic Life");

    db.begin();
    db.update(a1);
    db.commit();

Afterwards, the database looks like this:

Author

id | name
--- | ---
1 | "John Jackson"

Book

id | title | author_id
--- | --- | ---
1 | "My Fantastic Life" | 1

## Limitations

- To-many relationships are currently not supported (except many-to-one).

- As it is now, enabling cascading update will cause db.update() to also create any entities that have not yet been persisted. (In other words: setting cascading to "update" has the same effect as setting it to "update create", but only when invoking db.update().)

## See also

- How to use cascading operations - overview