i have many to many relationship between book and author, i have 3 tables: author, book and author_book.
@Entity()
@Table(name = "author")
public class Author implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
name = "author_book",
joinColumns = @JoinColumn(name = "author_id"),
inverseJoinColumns = @JoinColumn(name = "book_id")
)
private List<Book> authorBooks = new ArrayList<Book>();
public Author() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getAuthorBooks() {
return authorBooks;
}
public void setAuthorBooks(List<Book> authorBooks) {
this.authorBooks = authorBooks;
}
@Override
public String toString() {
return "Author{" + "name=" + name + ", authorBooks=" + authorBooks + '}';
}
}
@Entity()
@Table(name = "book")
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(mappedBy = "authorBooks", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Author> bookAuthors = new ArrayList<Author>();
public Book() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Author> getBookAuthors() {
return bookAuthors;
}
public void setBookAuthors(List<Author> bookAuthors) {
this.bookAuthors = bookAuthors;
}
@Override
public String toString() {
return "Book{" + "name=" + name + ", bookAuthors=" + bookAuthors + '}';
}
}
i can add data to db without a problem, but when i want to get an author or a book by its id
Optional<Author> optionalAuthor = authorReposi.findById(1L);
System.out.println("Author: " + optionalAuthor.get().toString());
i get an error: LazyInitialization failed to lazily ...
I want to use FetchType.LAZY and get the instance of author or book.
Thank you for your time.