Answer the question
In order to leave comments, you need to log in
How to get the correct entity in the DAO layer using JDBC?
There is a program with entities Author, Book, Genre which are connected with each other as many to many.
There are tables in the database to store them and provide links between them.
In java code:
public class Author {
...
private List<Book> books;
private List<Genre> genres;
}
public class Book {
...
private List<Author> authors;
private List<Genre> genres;
}
public class Genre {
...
private List<Author> authors;
private List<Book> books;
}
CREATE TABLE author (
`author_id` INT NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT,
...
);
CREATE TABLE book (
`book_id` INT NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT,
...
);
CREATE TABLE genre (
`genre_id` INT NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT,
...
);
CREATE TABLE author_book (
`author_id` INT NOT NULL REFERENCES author(author_id),
`book_id` INT NOT NULL REFERENCES book(book_id),
UNIQUE KEY `author_book_unique_id` (`author_id`,`book_id`)
);
CREATE TABLE author_genre (
`author_id` INT NOT NULL REFERENCES author(author_id),
`genre_id` INT NOT NULL REFERENCES genre(genre_id),
UNIQUE KEY `author_genre_id` (`author_id`,`genre_id`)
);
CREATE TABLE book_genre (
`book_id` INT NOT NULL REFERENCES book(book_id),
`genre_id` INT NOT NULL REFERENCES genre(genre_id),
UNIQUE KEY `book_genre_id` (`book_id`,`genre_id`)
);
Answer the question
In order to leave comments, you need to log in
Good afternoon.
In Hibernate, when using the ManyToMany annotation, 3 tables are created. 2 tables for the entities themselves, where information is stored and 1 table with mappings, where the id of the entities are stored. In this case, your tables are fine.
The returned author must have the books and genres fields initialized. There should be
books that the author wrote and the genres in which he worked. In turn, each book should have
information in what genre it is written and what authors it has. A genre should store a list of books related to it
and authors working in this genre.
Thus, returning the author to the service layer, we must load a bunch of information from the database, and this will not be one request, but a lot.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question