Let I have Tables (Books and Authors have ManyToMany relation ship)
BOOKS
id
book_name
AUTHORS
id
author_name
BOOKS_AUTHORS
id
book_id
author_id
I map this Tables on Entities
class Books
{
@Id
long id;
@Column(name = "author_name")
String name;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "BOOKS_AUTHORS",
joinColumns = @JoinColumn(name = "book_id"),
inverseJoinColumns = @JoinColumn(name = "author_id"))
List<Authots> authors;
// setter, getters, adder
}
class Authors
{
@Id
long id;
@Column(name = "author_name")
String name;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "BOOKS_AUTHORS",
joinColumns = @JoinColumn(name = "author_id"),
inverseJoinColumns = @JoinColumn(name = "book_id"))
List<Books> books;
// setter, getters, adder
}
Now, I try do next
public void addAuthor(final String bookName, final Author author)
{
final Book book = // get book from database by bookName
if (book == null)
throw new DataNotFoundException("Book not found :(");
author.addBook(book);
book.addAuthor(author);
entityManager.persist(author);
}
1) I get exception that ID of BOOKS_AUTHORS record must be not NULL
2) How I can Generate ID (ising sequance generator) for relationship-table BOOKS_AUTHORS
You cannot use @ManyToMany
to create join table with id field in it.
If id field in the join table is a requirement, you have to create a special entity class (such as BookAuthor
) for that table and connect it with books and authors with @ManyToOne
/@OneToMany
relationships.
Otherwise you need to remove id field from BOOKS_AUTHORS
table.
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
If books_authors
is not mapped using Hibernate, then use the database side auto id incrementor. Example:
ALTER table book_authors CHANGE id long NOT NULL AUTO_INCREMENT;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With