I am developing Spring Boot app with Spring Data JPA and H2 database. I am using spring-data-jpa. When I use ManyToMany mapper class to get the data of another class. But I found it is NULL.
Book.class
@Entity
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "BOOK_AUTHOR", joinColumns = {
@JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")}, inverseJoinColumns = {
@JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")})
private Set<Author> authors;
public Book() {
super();
}
public Book(String name) {
super();
this.name = name;
this.authors = new HashSet<>();
}
public Book(String name, Set<Author> authors) {
super();
this.name = name;
this.authors = authors;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Author> getAuthors() {
return authors;
}
public void setAuthors(Set<Author> authors) {
this.authors = authors;
}
@Override
public String toString() {
return String.format("Book [id=%s, name=%s, authors=%s]", id, name, authors);
}
}
Author.class
@Entity
public class Author implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Integer id;
private String name;
@ManyToMany(mappedBy = "authors")
private Set<Book> books;
//why CAN NOT GET the data when using these code else ?
// @ManyToMany(cascade = CascadeType.ALL)
// @JoinTable(name = "BOOK_AUTHOR", joinColumns = {
// @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID")},
//inverseJoinColumns = {
// @JoinColumn(name = "BOOK_ID", referencedColumnName = "ID")})
// private Set<Book> books;
public Author() {
super();
}
public Author(String name) {
super();
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
@Override
public String toString() {
return String.format("Author [id=%s, name=%s, books=%s]", id, name, books);
}
}
Test code snapper in test.class
List<Book> books = bookRepository.findAll();
for (Book it : books) {
Set<Author> authors = it.getAuthors();
//CAN get authors data.
System.out.println(authors.size());
}
assertThat(bookRepository.findAll()).hasSize(2);
List<Author> authors = authorRepository.findAll();
for (Author it : authors) {
//CAN NOT get books data ? Why and HOW ?
//HOW can I get the books data ? Or other ways ?
// thanks
Set<Book> books1 = it.getBooks();
assertThat(books1 == null);
}
assertThat(authorRepository.findAll()).hasSize(3);
Is there some error in my code ? Or other ways ?
Thanks vary much.