【发布时间】:2018-02-05 13:14:06
【问题描述】:
假设我有:
- 表editors(id、business_name、vat)
- 表作者(id、姓名、电子邮件)
- 表书籍(id、标题、描述、fk_author、fk_editor)。
假设 fk_editor 是表编辑器的 id 字段的外键,fk_author 是表作者的 id 字段的外键。
假设关系 books:authors 是 n:1 并且 books:editors 是 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 */
}
【问题讨论】: