How to cascade deletion

# How to cascade deletion

## Overview

If you enable cascading deletion on a relationship, deleting the object on one end of the relationship (i.e. calling db.remove() on the object) will also delete the object on the other end.

## Enabling cascading deletion

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

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

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

## Scenarios

### db.remove()

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, since we specified the relationship to cascade deletion, if we remove the book, the author gets removed too (after all, an author without a book isn't really an author).

    db.begin();

    Book b1 = db.load(Book.class, 1);
    db.remove(db1);

    db.commit();

Afterwards, the database predictably looks like this:

Author

id | name
--- | ---
(empty table)

Book

id | title | author_id
--- | --- | ---
(empty table)

Cascading the deletion of objects in to-many relationships works in exactly the same way.

Note: You need to explicitly invoke db.remove() to delete an object. Simply setting a relational property to NULL or removing an item from a collection will not remove the corresponding entity from the database, even with cascading deletion enabled.

## See also

- How to use cascading operations - overview