Here is my code
public class Start {
public static void main(String[] args) {
AuthorHelper authorHelper = new AuthorHelper();
Author author1 = authorHelper.getAuthor(4L);
author1.setName("TEST");
authorHelper.updateAuthor(author1);
List<Author> authorList = authorHelper.getAuthorList();
authorList.forEach(author -> {
System.out.println(author.getName());
System.out.println("Books");
System.out.println("--------------------------------------------------------------------------------");
author.getBooks().forEach(book1 -> {
System.out.println(book1.getTitle());
});
});
}
}
When I am trying to get books from author i get this:
Exception in thread "main" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: entity.Author.books: could not initialize proxy - no Session
Here is my getAuthorList method:
public List<Author> getAuthorList() {
List<Author> authorList;
Session session = sessionFactory.openSession();
authorList = session.createQuery("SELECT a FROM Author a", Author.class).list();
session.close();
return authorList;
}
I tried to use JOIN FETCH, but if I undersand it correctly - hibernate will fetch all authors and all books from db, but thats not what i want, because it is not always necessarily to get books from authors. I think the problem is in List because it contains detached entities and no Session open. I also tried to use
Hibernate.initialize(author.getBooks());
Before getting books, but it is still not working, any ideas how to fix that?