未填充双向多对多关系的联接表-Java Spring

时间:2018-12-11 02:30:12

标签: java spring many-to-many table-relationships

  

你好

     

我在两个表之间有双向的ManyToMany关系(“产品”   和“类别”)。我已经将产品播种到数据库中,每个   空的“类别”列表。当我现在尝试播种   带有完整产品清单的“类别”,我注意到   如果未在数据库中创建JoinedTable,则JoinedTable不会更新。   类别类。

     

我认为在双向关系中不应该存在   差异,无论您如何播种数据库,JoinedTable应该是   从双方更新。如果有人可以解释我将不胜感激   这是预期的行为以及原因。

@Entity
@Table(name = "categories")
public class Category implements Serializable {
    private long id;
    private String name;
    private List<Product> products;

@Entity
@Table(name = "products")
public class Product implements Serializable {
    private Long id;
    private String name;
    private List<Category> categories;
  1. 工作示例

当我为类别添加种子时,JoinedTable会正确更新。

Category.java

  @ManyToMany()
  @JoinTable(name = "product_category", 
  joinColumns = @JoinColumn(name = "category_id",referencedColumnName = "id"),
  inverseJoinColumns = @JoinColumn(name = "product_id", referencedColumnName = "id"))
  public List<Product> getProducts() {
  return this.products;}

Product.java

@ManyToMany(mappedBy = "products", targetEntity = Category.class)
public List<Category> getCategories() {
return this.categories;}
  1. 不起作用的示例

当我为“类别”添加种子时,JoinedTable不会更新。但是,我可以从两个类中访问带有产品和类别的列表。

Categoty.java

//I tried adding CascadeType.ALL however this didn’t fix the issue 

@ManyToMany(mappedBy = "categories", targetEntity = Product.class)
public List<Product> getProducts() {
return this.products;}

Product.java

@ManyToMany(targetEntity = Category.class)
@JoinTable(name = "product_category",
    joinColumns = @JoinColumn(name = "product_id", referencedColumnName = "id"),
    inverseJoinColumns = @JoinColumn(name = "category_id", referencedColumnName = "id"))
public List<Category> getCategories() {
return this.categories;}

0 个答案:

没有答案