在Spring Boot/Hibernate/JPA中为联接表指定表名和字段名
我使用的是MySQL支持的SpringBoot/JPA。我已经配置了DB,因此计划使用在Spring Boot/Hibernate/JPA中为联接表指定表名和字段名,hibernate,jpa,spring-boot,many-to-many,Hibernate,Jpa,Spring Boot,Many To Many,我使用的是MySQL支持的SpringBoot/JPA。我已经配置了DB,因此计划使用hibernate.hbm2ddl.auto=validate(因此hibernate不会尝试为我创建DB,而是使用我提供的DB,并根据我在代码中定义的实体对其进行“验证”) 我与我的实体有几个多对多的关系,例如Book和Author: // Groovy pseudo code! One book can have multiple authors, and a // single author can ha
hibernate.hbm2ddl.auto=validate
(因此hibernate不会尝试为我创建DB,而是使用我提供的DB,并根据我在代码中定义的实体对其进行“验证”)
我与我的实体有几个多对多的关系,例如Book
和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
}
其中,
books\u x\u authors
是我的多对多或“人行横道”表。这是一个DB命名约定,我非常喜欢,如果可能的话,我想坚持。那么,我如何配置Spring Boot/Hibernate以使用books\u x\u authors
作为我的联接/人行横道表,而不是期望一个表遵守它自己的约定呢?在您的许多目录下指定联接表以及您需要的所有内容
@ManyToMany
@JoinTable(name="books_x_authors",
joinColumns={@JoinColumn(name="author_id"}, inverseJoinColumns={@JoinColumn(name="book_id")} )
List<Book> books
@manytomy
@JoinTable(name=“books\u x\u authors”,
joinColumns={@JoinColumn(name=“author\u id”},inverseJoinColumns={@JoinColumn(name=“book\u id”)})
书目
谢谢@Amer Qarabasa(+1)-如果你不介意的话,可以问一个快速的后续问题!我假设在Book
类中,我必须做相反的操作,并将Book\u id
声明为joinColumns
,并且我必须将author\u id
声明为inverseJoinColumn
?或者我只是在一个类中定义一次吗?如果是这样,有关系吗r我在(Book
或Author
)中定义了哪些类的注释?再次感谢!如果您知道Author是此关系中的所有者,那么您只需将@manytomy(mappedBy=“books”)放在您的Book类中,无需进一步确认。如果答案解决了您的问题,请接受它作为答案:)
@ManyToMany
@JoinTable(name="books_x_authors",
joinColumns={@JoinColumn(name="author_id"}, inverseJoinColumns={@JoinColumn(name="book_id")} )
List<Book> books