多对多关联
比如现在有两个实体类:1. Product(商品)2. Category(类别)
一个商品可以有多个类别,一个类别也可以有多个商品,这就形成了多对多的关系
Product
package com.jpa.helloworld2;
import java.util.List;
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="T_PRODUCT")
@Entity
public class Product {
@GeneratedValue
@Id
@Column(name="ID")
private Integer id;
@Column(name="NAME")
private String name;
@JoinTable(name="PRODUCT_CATEGORY",//中间表的名称
joinColumns={@JoinColumn(name="PRODUCT_ID",referencedColumnName="ID")},//中间表PRODUCT_ID字段关联PRODUCT的ID
inverseJoinColumns={@JoinColumn(name="CATEGORY_ID",referencedColumnName="ID")})//中间表CATEGORY_ID字段关联CATEGORY的ID
@ManyToMany
private List<Category> categorys = new ArrayList<Category>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Category> getCategorys() {
return categorys;
}
public void setCategorys(List<Category> categorys) {
this.categorys = categorys;
}
}
Category
package com.jpa.helloworld2;
import java.util.List;
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="T_CATEGORY")
@Entity
public class Category {
@GeneratedValue
@Id
@Column(name="ID")
private Integer id;
@Column(name="NAME")
private String name;
@ManyToMany(mappedBy="categorys")
private List<Product> products = new ArrayList<Product>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
多对多关系需要用到第三张表,不过这张表不需要我们手动创建,JPA会根据我们使用注解配置的来帮我们创建,我们只需要写好上面的两个实体类即可。
JPA创建的三张表:
中间表中的外键关系
增加
Category category1 = new Category();
category1.setName("category1");
Category category2 = new Category();
category2.setName("category2");
Product product1 = new Product();
product1.setName("product1");
Product product2 = new Product();
product2.setName("product2");
category1.getProducts().add(product1);
category1.getProducts().add(product2);
category2.getProducts().add(product1);
category2.getProducts().add(product2);
product1.getCategorys().add(category1);
product1.getCategorys().add(category2);
product2.getCategorys().add(category1);
product2.getCategorys().add(category2);
entityManager.persist(category1);
entityManager.persist(category2);
entityManager.persist(product1);
entityManager.persist(product2);
查询
对于关联的集合对象,默认使用懒加载的策略
无论查询维护关联关系的一方,还是查询不维护关联关系的一方,SQL语句相同。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-05 18:37:38