简体   繁体   中英

JPA many to many persistence

I have 2 persistent classes with a many-to-many relationship between them: Supplier and Category.

Here's the relevant code:

Supplier:

@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...
}

Category:

@Entity
@Table(name="category")
public class Category {

    @ManyToMany
    Set<Supplier> suppliers = new HashSet<Supplier>();

    public void addSupplier(Supplier supplier) {
        if (suppliers.add(supplier)) {
            supplier.categories.add(this);
        }
    }

    //snip...       
}

As you can see, when adding a Supplier to a Category (or vice versa) both sides of the relationship are kept in sync with each other.

When I attempt to persist a new Supplier and add it to a pre-existing Category, however, the relationship is not persisted. A new row is successfully inserted into the Supplier table, but no corresponding row is inserted into the join table. There are no error messages.

here's my attempt:

    Category category = categoryRepo.findOne(categoryId);
    Supplier savedSupplier  = repo.save(supplier);
    savedSupplier.addCategory(category);

I'm usinig Spring Data, repo and categoryRepo extend Spring's JpaRepository .

You updated the inverse side of the relationship (Supplier), but not the owning side of the relationship (Category).

Try this:

Category category = categoryRepo.findOne(categoryId);
Supplier savedSupplier  = repo.save(supplier);
savedSupplier.addCategory(category);
category.addSupplier(savedSupplier);

Assuming your repo.save method operates in its own transaction/context, the relationship needs to be setup before the call to save the supplier. You will also need to set the cascade settings on the relationship, so that changes made to the referenced Category, specifically to its suppliers list, are picked up.

Or you can merge the category instance in the categoryRepo after you have made the changes to the relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM