Lazy Loading
Load only when needed.
An author might have thousands of books. Loading them all, every time we load the author, would be wasteful. So JPA waits, until we actually ask for them.
- Thousands of books
- Wasteful to load all
- Wait until asked
Eager and lazy
Eager means, load the related data straight away. Lazy means, load it later, the first time it's used. Many to one is eager by default, because it's just one object. One to many, and many to many, are lazy by default, because they can be huge.
| key | value |
|---|---|
| Eager | load now |
| Lazy | load on first use |
| @ManyToOne | eager by default |
| @OneToMany | lazy by default |
Lazy without a session
Here, the runner has no transaction. It loads author one, then asks for their books. Run it. Hibernate loads only the author. When we ask for the books, it's too late. The database session is already closed. So we get a lazy initialization exception.
@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) {
Author frank = authors.findById(1L).orElseThrow();
System.out.println("Loaded " + frank.getName());
try {
System.out.println(frank.getBooks().size() + " books");
} catch (RuntimeException e) {
System.out.println(e.getClass().getSimpleName());
}
}
}Hibernate: select a1_0.id,a1_0.name from author a1_0 where a1_0.id=? Loaded Frank Herbert LazyInitializationException
Also uses Author.java
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
protected Author() {}
public Author(String name) { this.name = name; }
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
}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
spring.jpa.show-sql=trueAlso uses _noddl
Lazy inside a transaction
Now run has at Transactional. The session stays open, until the method ends. Run it. First, Hibernate selects only the author. Then, when we ask for the books, it runs a second select. That's lazy loading working.
@Component
public class RelDemo implements CommandLineRunner {
private final AuthorRepository authors;
public RelDemo(AuthorRepository authors) { this.authors = authors; }
@Override
@Transactional
public void run(String... args) {
Author frank = authors.findById(1L).orElseThrow();
System.out.println("Loaded " + frank.getName());
System.out.println(frank.getBooks().size() + " books");
}
}Hibernate: select a1_0.id,a1_0.name from author a1_0 where a1_0.id=? Loaded Frank Herbert Hibernate: select b1_0.author_id,b1_0.id,b1_0.price,b1_0.title from book b1_0 where b1_0.author_id=? 2 books
Also uses Author.java
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author")
private List<Book> books = new ArrayList<>();
protected Author() {}
public Author(String name) { this.name = name; }
public Long getId() { return id; }
public String getName() { return name; }
public List<Book> getBooks() { return books; }
}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
spring.jpa.show-sql=trueAlso uses _noddl
Summary
Lazy relationships load on first use, which needs an open session, inside a transaction. Many to one is eager, and one to many is lazy. Next, cascade.
Key takeaways- Lazy = on first use
- Needs a transaction
- LazyInitializationException