Consider a Spring Boot JPA entity Author with a @OneToMany relationship to Book marked as fetch = FetchType.LAZY. When you fetch an Author from the database and access the list of Book entities for the first time, what happens?
public class Author { @OneToMany(mappedBy = "author", fetch = FetchType.LAZY) private List<Book> books; // getters and setters } // In service: Author author = authorRepository.findById(1L).get(); List<Book> books = author.getBooks();
Think about what FetchType.LAZY means for loading related entities.
With FetchType.LAZY, the related entities are not loaded immediately. Instead, they are loaded only when accessed for the first time, which helps improve performance by avoiding unnecessary data fetching.
Choose the correct way to define a bidirectional @OneToMany relationship between Author and Book entities in Spring Boot JPA.
Remember that mappedBy is used on the inverse side to point to the owning side's field.
The mappedBy attribute in @OneToMany tells JPA that the Book entity owns the relationship via its author field. The @ManyToOne side is the owning side and does not use mappedBy.
Given the following code, why does adding a new Book to the Author's books list not save the relationship in the database?
Author author = authorRepository.findById(1L).get();
Book newBook = new Book();
newBook.setTitle("New Book");
author.getBooks().add(newBook);
authorRepository.save(author);Think about which side owns the relationship and what fields must be set for JPA to persist it.
In a bidirectional @OneToMany relationship, the owning side is the Book entity with the author field. Adding a book to the author's list alone does not update the owning side. You must set newBook.setAuthor(author) for JPA to persist the relationship.
Given the following entities and code, what is the size of author.getBooks() after execution?
@Entity
class Author {
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List books = new ArrayList<>();
}
@Entity
class Book {
@ManyToOne
private Author author;
}
// Code:
Author author = new Author();
Book book1 = new Book();
book1.setAuthor(author);
Book book2 = new Book();
// book2.setAuthor(author); // missing
author.getBooks().add(book1);
author.getBooks().add(book2);
int size = author.getBooks().size(); Consider what the books list contains after adding both books.
The books list contains both book1 and book2 because both were added. The author field on book2 is not set, but that does not affect the list size. The list size is 2.
In a Spring Boot JPA entity, what happens if you define a @OneToMany relationship without specifying the mappedBy attribute?
Think about how JPA manages ownership of relationships and what happens without mappedBy.
When mappedBy is omitted in a @OneToMany, JPA assumes this side owns the relationship and creates a join table to manage it. This differs from the bidirectional case where the foreign key is in the child table.