0
假設我有:JPA外鍵連接同名
- 表編輯(ID,BUSINESS_NAME,增值稅)
- 表作者(ID,姓名,電子郵件)
- 表書籍(id,title,description,fk_author,fk_editor)。
比方說fk_editor是表格編輯器的ID字段和fk_author外鍵是表作者的ID字段的外鍵。
假設的關係書:作者是N:1周和書:編輯是N:1。
問題是:如何通過書籍表加入三張表表? 這意味着,我必須在Book類中添加哪些代碼才能讓Hibernate理解並與作者和編輯者建立關係?請考慮我在作者和編輯者中擁有相同的id字段名稱。 在這裏它的示例代碼,我需要糾正:
表作者:
package com.bytecode.jpaexample.SpringBootMySqlJpaRestExample;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "authors")
public class Author implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@OneToMany(fetch = FetchType.LAZY)
private int id;
@Column(name = "name")
private String name;
@Column(name = "surname")
private String surname;
@Column(name = "email")
private String email;
/* constructors and getters and setters omitted intentionally */
}
表編輯:
package com.bytecode.jpaexample.SpringBootMySqlJpaRestExample;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "editors")
public class Editor implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
@OneToMany(fetch = FetchType.LAZY)
private int id;
@Column(name = "business_name")
private String businessName;
@Column(name = "vat")
private String vat;
/* constructors and getters and setters omitted intentionally */
}
表書:
package com.bytecode.jpaexample.SpringBootMySqlJpaRestExample;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name="books")
public class Book implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id") //authors.id
@Column(name = "fk_author")
private int fk_editor;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id") //editors.id
@Column(name = "fk_editor")
private int fk_editor;
/* constructors and getters and setters omitted intentionally */
}
兩