Cascade
Save the family together.
When we save a new author, with new books, we'd like the books to be saved too. Without asking separately for each one. That's what cascade does.
- New author, new books
- Save them together
- Cascade
Author with cascade
Cascade type all passes every operation, from the author, to its books. Save the author, and its books are saved. Delete the author, and its books go too. Orphan removal also deletes a book, removed from the list. And add book creates a book, linked to this author.
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books = new ArrayList<>();
protected Author() {}
public Author(String name) { this.name = name; }
public void addBook(String title, double price) {
books.add(new Book(title, price, this));
}
public Long getId() { return id; }
public String getName() { return name; }
}Saving the family
We count the books, then create a new author, with two new books. We save only the author. Run it. There were five books. The author got id four. And now there are seven books, because the cascade saved both.
@Component
public class RelDemo implements CommandLineRunner {
private final AuthorRepository authors;
private final BookRepository books;
public RelDemo(AuthorRepository a, BookRepository b) { authors = a; books = b; }
@Override
public void run(String... args) {
System.out.println("Books before: " + books.count());
Author ursula = new Author("Ursula K. Le Guin");
ursula.addBook("A Wizard of Earthsea", 8.99);
ursula.addBook("The Left Hand of Darkness", 9.99);
authors.save(ursula);
System.out.println("Saved author " + ursula.getId());
System.out.println("Books after: " + books.count());
}
}INFO BookshopApplication : Started BookshopApplication in 4.228 seconds
Also uses Author.java
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books = new ArrayList<>();
protected Author() {}
public Author(String name) { this.name = name; }
public void addBook(String title, double price) {
books.add(new Book(title, price, this));
}
public Long getId() { return id; }
public String getName() { return name; }
}Also uses Book.java
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private double price;
@ManyToOne
private Author author;
protected Book() {}
public Book(String title, double price, Author author) {
this.title = title; this.price = price; this.author = author;
}
public Long getId() { return id; }
public String getTitle() { return title; }
public double getPrice() { return price; }
public Author getAuthor() { return author; }
}Also uses AuthorRepository.java
public interface AuthorRepository extends JpaRepository<Author, Long> {}Also uses BookRepository.java
public interface BookRepository extends JpaRepository<Book, Long> {}Also uses data.sql
INSERT INTO author (name) VALUES ('Frank Herbert'), ('J.R.R. Tolkien'), ('Madeline Miller');
INSERT INTO book (title, price, author_id) VALUES
('Dune', 9.99, 1), ('Children of Dune', 8.49, 1),
('The Hobbit', 8.99, 2), ('Circe', 10.99, 3), ('Song of Achilles', 9.49, 3);Also uses application.properties
spring.jpa.defer-datasource-initialization=trueUse cascade carefully
Use cascade from a parent, to children it owns, like an order, and its lines. Avoid it towards shared things. Cascading delete from a book, to its author, would delete the author, and every other book! So think, does the parent really own the child?
| key | value |
|---|---|
| Good | order → order lines |
| Good | author → their books (here) |
| Bad | book → author |
| Ask | does the parent own it? |
Summary
Cascade passes operations like save, and delete, from a parent to its children. Use it only where the parent owns the child. Next, many to many.
Key takeaways- cascade = ALL
- orphanRemoval
- Only for owned children