AI Hints
Home›Spring Boot Tutorial›Lazy Loading, Cascade and Many to Many
Spring Boot · Lesson 68 of 120

Cascade

Save the family together.

⏱ 2 min read▶ Video at 1:31:51🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

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.

Author.javajava
@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.

RelDemo.javajava
@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());
    }
}
Output
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=true

Use 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?

keyvalue
Goodorder → order lines
Goodauthor → their books (here)
Badbook → author
Askdoes 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
Next up: Many to Many — books and tags