I am using Spring Boot/JPA backed by MySQL. I already have the DB provisioned and so plan on using hibernate.hbm2ddl.auto = validate
(so Hibernate doesn't try to create a DB for me, it instead uses the one I supply and "validates" it against the entities I define in the code).
I have several many-to-many relationships with my entities, such as Book
and Author
:
// Groovy pseudo code! One book can have multiple authors, and a
// single author can have written many books.
@Entity
class Book {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long id
@Column(name="title")
String title
@ManyToMany
List<Author> authors
}
@Entity
class Author {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long id
@Column(name="name")
String name
@ManyToMany
List<Book> books
}
Here, those classes are represented by the following tables:
[books]
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT # PRIMARY KEY
title VARCHAR(50) NOT NULL
[authors]
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT # PRIMARY KEY
name VARCHAR(100) NOT NULL
[books_x_authors]
books_x_authors_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT # PRIMARY KEY
book_id # FK on books
author_id # FK on authors
Where books_x_authors
is my many-to-many or "crosswalk" table. Thats a DB naming convention I really like and want to stick with if at all possible. So how do I configure Spring Boot/Hibernate to use books_x_authors
as my join/crosswalk table instead of expecting perhaps a table adhering to its own conventions?
Under your ManyToMany specify the join table with all what you need
@ManyToMany
@JoinTable(name="books_x_authors",
joinColumns={@JoinColumn(name="author_id"}, inverseJoinColumns={@JoinColumn(name="book_id")} )
List<Book> books
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