JPA:對映雙向多對多關聯關係
.在雙向多對多關係中,我們必須指定一個關係維護端(owner side),可以通過@ManyToMany註釋中指定
mappedBy屬性來標識其為關係維護端
1.這裡用商品(Item)和類別(Category)舉例子,一個商品可以對應多個種類,而一個種類也可以對應多個商品.
2.商品實體類Item程式碼如下:
package com.wayne.helloworld;
/*
* 商品
*/
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Table(name="JPA_ITEMS")
@Entity
public class Item {
private Integer id;
private String itemName;
private Set<Category> categories = new HashSet<>();
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="ITEM_NAME")
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
/*
* 使用ManyToMany註解來對映多對多關聯關係
* 使用@JoinTable來對映中間表
* 1.name指向中間表的名字
* 2.joinColumns對映當前類所在的表在中間表中的外來鍵
* 3.joinColumns的name元素指外來鍵列的列名
* 4.referenceColumnName指定外來鍵列關聯當前表的哪一列
* 5.inverseJoinColumns對映關聯的類所在的中間表的外來鍵
*/
@JoinTable(name="ITEM_CATEGORY",
joinColumns={@JoinColumn(name="ITEM_ID",referencedColumnName="ID")},
inverseJoinColumns={@JoinColumn(name="CATEGORY_ID",referencedColumnName="ID")})
@ManyToMany
public Set<Category> getCategories() {
return categories;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
}
3.類別實體類Category程式碼如下:
package com.wayne.helloworld;
/*
* 類別
*/
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Table(name="JPA_CATEGORIES")
@Entity
public class Category {
private Integer id;
private String categoryName;
private Set<Item> items = new HashSet<>();
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="CATEGORY_NAME")
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
@ManyToMany(mappedBy="categories")
public Set<Item> getItems() {
return items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
}
4.插入資料程式碼如下:
5.查詢程式碼片段如下及控制檯輸出如下,首先我們查詢關聯的物件:
.對於關聯的集合物件,預設使用懶載入的策略
.對於不關聯的集合物件,也一樣,兩者SQL語句是相同的,這裡不做過多贅述