Java JPA多对多持久性
我有两个持久类,它们之间有多对多关系:Supplier和Category 以下是相关代码: 供应商:Java JPA多对多持久性,java,spring,jpa,spring-data-jpa,Java,Spring,Jpa,Spring Data Jpa,我有两个持久类,它们之间有多对多关系:Supplier和Category 以下是相关代码: 供应商: @Entity @Table(name="supplier") public class Supplier { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @ManyToMany(fetch=FetchType.LAZY, mappedBy="suppliers") Set&l
@Entity
@Table(name="supplier")
public class Supplier {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private int id;
@ManyToMany(fetch=FetchType.LAZY, mappedBy="suppliers")
Set<Category> categories = new HashSet<Category>();
public void addCategory(Category category) {
if (categories.add(category)) {
category.suppliers.add(this);
}
}
//snip...
}
我正在使用Spring数据,
repo
和categoryRepo
扩展Spring的JpaRepository
您更新了关系的反面(供应商),但没有更新关系的拥有方(类别)
试试这个:
Category category = categoryRepo.findOne(categoryId);
Supplier savedSupplier = repo.save(supplier);
savedSupplier.addCategory(category);
category.addSupplier(savedSupplier);
假设repo.save方法在其自己的事务/上下文中运行,则需要在调用保存供应商之前设置关系。您还需要在关系上设置级联设置,以便拾取对引用类别(特别是其供应商列表)所做的更改
或者,在对关系进行更改后,您可以将CategoryReporto中的category实例合并。在JPA中,我认为在这种情况下,
ManyToMany
的一方必须“拥有”关系,并因此负责更新联接表。@CollinD,拥有关系的一方是不具有mappedBy属性的一方-在本例中,类别实体是关系的所有者,而供应商是关系的反面。请参阅问题中的代码段:addCategory()
方法还将此供应商添加到指定类别中。
Category category = categoryRepo.findOne(categoryId);
Supplier savedSupplier = repo.save(supplier);
savedSupplier.addCategory(category);
Category category = categoryRepo.findOne(categoryId);
Supplier savedSupplier = repo.save(supplier);
savedSupplier.addCategory(category);
category.addSupplier(savedSupplier);