JPA多对多的关联关系
/**
*
*/
package com.jpa.helloword;
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;
/**
* @author 徐庶
* @date 2017年1月14日
*/
@Table(name="JPA_ITEMS")
@Entity
public class Item {
private Integer id;
private String itemName;
private Set<Category> cas=new HashSet<>();
@Id
@GeneratedValue
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;
}
/**
*使用 @JoinTable来映射中间表
*1.name指向中间表的名字
*2.joinColumns映射当前类所在中间表的外键
* 2.1name指定外键列的名称
* 2.2referencedColumnName指定外键列关联当前表的哪一列
*3.inverseJoinColumns映射关联的类所在中间表的外键
*/
@JoinTable(name="item_category",joinColumns={@JoinColumn(name="item_id",referencedColumnName="id")},
inverseJoinColumns={@JoinColumn(name="category_id",referencedColumnName="id")})
@ManyToMany
public Set<Category> getCas() {
return cas;
}
public void setCas(Set<Category> cas) {
this.cas = cas;
}
}
/**
*
*/
package com.jpa.helloword;
import java.util.HashSet;
import java.util.Set;
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;
/**
* @author 徐庶
* @date 2017年1月14日
*/
@Table(name="JPA_CATEGORY")
@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;
}
@JoinColumn(name="category_name")
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
//指向维护关系的一方
@ManyToMany(mappedBy="cas")
public Set<Item> getItems() {
return items;
}
public void setItems(Set<Item> items) {
this.items = items;
}
}
测试类:
//多对多保存
@Test
public void testManyTomany(){
Item it1=new Item();
it1.setItemName("A-ti1");
Item it2=new Item();
it2.setItemName("A-it2");
Category c1=new Category();
c1.setCategoryName("B-c1");
Category c2=new Category();
c2.setCategoryName("B-c2");
//设置关联关系
it1.getCas().add(c1);
it1.getCas().add(c2);
it2.getCas().add(c1);
it2.getCas().add(c2);
c1.getItems().add(it1);
c1.getItems().add(it2);
c2.getItems().add(it1);
c2.getItems().add(it2);
//保存
entityManager.persist(it1);
entityManager.persist(it2);
entityManager.persist(c1);
entityManager.persist(c2);
}
//多对多的查找,默认使用懒加载方式
@Test
public void testManyTomanyFind(){
Item item = entityManager.find(Item.class, 1);
System.out.println(item);
Set<Category> cas = item.getCas();
System.out.println(cas.size());
}