Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying table and field names for join tables in Spring Boot/Hibernate/JPA

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?

like image 369
smeeb Avatar asked Mar 09 '23 10:03

smeeb


1 Answers

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
like image 102
Amer Qarabsa Avatar answered Mar 12 '23 04:03

Amer Qarabsa