一個作者(Author)有多本書(Book),JPA 雙向一對多/多對一實體關聯設定如下。
Author.java
@Entity
@Table(name="Author")
public class Author {
@Id
@Column(name="AuthorId")
private Integer authorId;
@Column(name="AuthorName")
private String authorName;
@OneToMany(mappedBy="author")
private Set&t;Book> bookSet;
// getter and setter ommitted...
}
Book.java
@Entity
@Table(name="Book")
public class Book {
@Id
@Column(name="BookId")
private Integer bookId;
@Column(name="BookName")
private String bookName;
@ManyToOne
@JoinColumn(name="AuthorId") // 外鍵欄位名稱
private Author author; // 外鍵屬性
// getter and setter ommitted...
}
@JoinColumn
要放在外鍵所在的實體(owning side)的外鍵屬性。Book
持有Author
的外鍵,所以@JoinColumn
放在Book.author
@OneToMany
放在non owning side的實體,並設定mappedBy
,其值為關係實體外鍵屬性的名稱。
參考:
- Hibernate JPA 雙向關係 Bidirectional Relationships 的意思
- Spring Data JPA @OneToMany LazyInitializationException could not initialize proxy - no Session
- JPA JoinColumn vs mappedBy
- What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?
- Hibernate/JPA ManyToOne vs OneToMany
- JPA: Determining the Owning Side of a Relationship
- In a bidirectional JPA OneToMany/ManyToOne association, what is meant by “the inverse side of the association”?
- JPA - Bidirectional OneToMany/ManyToOne Example
沒有留言:
張貼留言