我有2个实体商店和产品具有多对多关系,PlayFramework创建了一个表product_shop,它存储了shop_id,product_id,但每当我添加新产品时,先前的product_id行被删除,新的存储在product_shop中表
Product.java
package models;
@Entity
public class Product extends Model {
@Id
public Long id;
@Required
public String name;
@Required
public Float price;
@OneToOne
@Required
public String category;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name="product_shop",
joinColumns=
@JoinColumn(name="product_id", referencedColumnName="ID"),
inverseJoinColumns=
@JoinColumn(name="shop_id", referencedColumnName="ID")
)
public List<Shop> shops=new ArrayList<>();
public List<Shop> getShops(){return shops;}
public static List<Product> findbyid(String mail) {
return find.where().eq("owner_email", mail).findList();
}
public static List<Product> all() {
return find.all();
}
public static Model.Finder<Long, Product> find = new Model.Finder<>(Long.class, Product.class);
public static Product create(Product product,Shop shop) {
product.save();
// product.saveManyToManyAssociations("shops");
List<Product> products = new ArrayList<>();
products.add(product);
shop.products = products;
shop.save();
return product;
}
}
Shop.java
package models;
@Entity
public class Shop extends Model {
@Id
public Long id;
@Required
public String name;
@Required
public String addressLine1;
public String addressLine2;
public String addressLine3;
@Required
public String city;
@Required
public String town;
@Required
public String phoneNumber;
@ManyToMany(mappedBy = "shops")
public List<Product> products=new ArrayList<>();
@Required
@OneToOne
public String category;
@Lob
@Column(name = "shop_pic")
public byte[] shop_pic;
@ManyToOne
@Required
public User owner;
public static Shop create(Shop shop) {
shop.save();
return shop;
}
}
答案 0 :(得分:0)
问题出在Product类的'create'方法中 此方法创建新列表并向其添加产品。然后它将此列表分配给商店 这样做会覆盖以前的产品列表。 要解决这个问题,我们所要做的就是将'create'方法更改为以下内容:
public static Product create(Product product,Shop shop) {
shop.products.add(product);
product.shops.add(shop);
product.save();
return product;
}