Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JPA多对多持久性_Java_Spring_Jpa_Spring Data Jpa - Fatal编程技术网

Java JPA多对多持久性

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

我有两个持久类,它们之间有多对多关系:Supplier和Category

以下是相关代码:

供应商:

@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);