I have tables Authors and Books (with join table Authorsbooks) in database. I created and initiated tables with MySQL
. I have also made (a standard) JPA
mapping with two entities Authors and Books using @manyToMany
and @Jointable
in one entity and mappedBy
in the other and connected it to database.
When I try to get all members of Authors entity with Java with method findAll()
it returns an endless sequence: like a first member of authors with list of books, in which a first Book contain list of Authors where it contain first Book which contain list of authors and so on, endless. How to get only authors w/o field listOfBooks (like I have it in the database table)?
@Entity
public class Author {
@Id
@GeneratedValue
@Column(name = "authorid")
private Integer authorid;
@Column(name = "authorname")
private String authorname;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "listOfAuthors")
private List<Book> listOfBooks = new ArrayList<Book>();
//getters and setters
@Entity
public class Book {
@Id
@GeneratedValue
@Column(name = "bookid")
private Integer bookid;
@Column(name = "bookname")
private String bookname;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "author2books", joinColumns = @JoinColumn(name = "bookid"),
inverseJoinColumns = @JoinColumn(name = "authorid"))
private List<Author> listOfAuthors = new ArrayList<Author>();
//getters and setters
@RestController
@RequestMapping(value = "/rest/authors") public class AuthorResource {
@Autowired
AuthorsRepository authorsRepository;
@GetMapping(value = "/all")
public List<Author> getAll() {
return authorsRepository.findAll();
}
}
CREATE TABLE author
( authorid INT AUTO_INCREMENT PRIMARY KEY, authorname VARCHAR(255) NOT NULL );
CREATE TABLE Book ( bookid INT AUTO_INCREMENT PRIMARY KEY, bookname VARCHAR(255) NOT NULL );
CREATE TABLE author2books ( authorid INT, bookid INT,
PRIMARY KEY (authorid, bookid), FOREIGN KEY (authorid) REFERENCES Author (authorid), FOREIGN KEY (bookid) REFERENCES Book (bookid) );
-- Create Author values INSERT INTO Author VALUES (authorid, 'Sven'); INSERT INTO Author VALUES (authorid, 'Peter');
-- Create Book values INSERT INTO Book VALUES (bookid, 'Biology'); INSERT INTO Book VALUES (bookid, 'Chemistry');
-- Create author2books values
INSERT INTO author2books VALUES (1, 2);