I’m working on a Spring Boot application using JPA and Hibernate for ORM. I have a problem with lazy loading and transactions that I can’t seem to resolve.
Here is my setup:
Spring Boot 2.5.2
Hibernate 5.4.32
MySQL 8.0.25
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy = "author", fetch = FetchType.LAZY)
private List<Book> books;
// Getters and setters
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private Author author;
// Getters and setters
}
@Service
public class AuthorService {
@Autowired
private AuthorRepository authorRepository;
@Transactional
public Author getAuthorWithBooks(Long authorId) {
Author author = authorRepository.findById(authorId).orElseThrow(() -> new EntityNotFoundException("Author not found"));
// Trying to access lazy-loaded books
author.getBooks().size();
return author;
}
}
public interface AuthorRepository extends JpaRepository<Author, Long> {
}
When I call the getAuthorWithBooks method, it throws a LazyInitializationException if the author.getBooks().size() line is executed outside of the transactional method. However, I was under the impression that the @Transactional annotation would handle this.
How can I ensure that the books collection is properly loaded within the transactional context? Is there a better way to handle this kind of lazy loading in JPA?
goose is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.