Consider a Spring Boot JPA entity with a @OneToMany(fetch = FetchType.LAZY) collection. What will happen if you try to access this collection after the transaction has closed?
public class Author { @OneToMany(fetch = FetchType.LAZY, mappedBy = "author") private List<Book> books; public List<Book> getBooks() { return books; } } // In service method with @Transactional Author author = authorRepository.findById(1L).get(); // Transaction ends here List<Book> books = author.getBooks(); // What happens here?
Think about when the data is actually loaded from the database with LAZY fetch.
LAZY fetch means the collection is loaded only when accessed inside an open session/transaction. Accessing it outside causes a LazyInitializationException.
Given the following entity snippet, what is the default fetch type for the @ManyToOne association?
public class Book { @ManyToOne private Author author; public Author getAuthor() { return author; } }
Check the JPA specification defaults for @ManyToOne.
By default, @ManyToOne associations are fetched eagerly, meaning the related entity is loaded immediately with the parent.
Choose the correct way to declare a @OneToOne association with LAZY fetching in Spring Data JPA.
Look carefully at the attribute name and enum usage in the annotation.
The correct attribute name is fetch and the value must be FetchType.LAZY. Other options have syntax errors or wrong attribute names.
Given this entity relationship, why might setting fetch = FetchType.EAGER on a @OneToMany cause performance problems?
public class Author { @OneToMany(fetch = FetchType.EAGER, mappedBy = "author") private List<Book> books; }
Think about what happens when many related entities are loaded eagerly.
EAGER fetch loads all related entities immediately, which can cause large joins or multiple queries, slowing down performance especially with large collections.
In a Spring Boot REST controller, if you return an entity with LAZY loaded associations, what is the typical behavior when serializing to JSON?
Consider when the Hibernate session is open and how Jackson serializes proxies.
By default, the Hibernate session is closed before serialization, so accessing LAZY proxies causes LazyInitializationException during JSON serialization.