Consider a JPA entity Author with a @OneToMany relationship to Book marked as fetch = FetchType.LAZY. What will happen when you access the books collection outside a transaction?
public class Author { @OneToMany(fetch = FetchType.LAZY, mappedBy = "author") private List<Book> books; // getters and setters } // In a service method without transaction Author author = authorRepository.findById(1L).orElseThrow(); List<Book> books = author.getBooks(); // What happens here?
Think about how lazy loading works and when the database session is active.
Lazy loading defers loading the related entities until accessed. If accessed outside a transaction or session, JPA cannot fetch the data and throws LazyInitializationException.
Given two entities Order and OrderItem, which option correctly sets up a bidirectional relationship where one order has many order items?
public class Order { // relationship here } public class OrderItem { // relationship here }
Remember that mappedBy goes on the inverse side and @JoinColumn on the owning side.
The Order entity is the inverse side with mappedBy. The OrderItem owns the relationship with @JoinColumn. This setup is correct for bidirectional OneToMany/ManyToOne.
Given an Author entity with a @OneToMany(cascade = CascadeType.PERSIST) relationship to Book, what happens when you persist the author with new books added?
Author author = new Author(); author.setName("Jane Doe"); Book book1 = new Book(); book1.setTitle("Book One"); Book book2 = new Book(); book2.setTitle("Book Two"); author.setBooks(List.of(book1, book2)); entityManager.persist(author); // What is the state of book1 and book2 after this?
Think about what cascade persist means for related entities.
CascadeType.PERSIST causes JPA to persist all related entities automatically when the parent is persisted. So both books are saved along with the author.
Given these entities with bidirectional relationships, serializing Author to JSON causes infinite recursion. Why?
public class Author { @OneToMany(mappedBy = "author") private List<Book> books; // getters and setters } public class Book { @ManyToOne private Author author; // getters and setters } // Serialization code: ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(author);
Think about how JSON serialization handles circular references.
Bidirectional relationships cause infinite recursion during serialization because each side references the other endlessly. This must be handled with annotations like @JsonManagedReference and @JsonBackReference or similar.
In JPA, relationships have owning and inverse sides. Why does this distinction matter?
Consider which side JPA uses to manage the foreign key column in the database.
The owning side is responsible for managing the foreign key column in the database. The inverse side is just a mirror and does not update the database. This prevents conflicts and keeps data consistent.