我有2个实体Shop和Product具有多对多关系,PlayFramework创建了一个表product_shop,该表存储shop_id,product_id,但是每次我添加新产品时,都会删除先前的product_id行,并将新行存储在product_shop表中。

产品.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;
    }
}

最佳答案

问题出在Product类的'create'方法中。
此方法创建新列表并向其中添加产品。然后,它将此列表分配给商店。
这样做会覆盖以前的产品列表。
为了解决这个问题,我们要做的就是将“ create”方法更改为以下内容:

public static Product create(Product product,Shop shop) {
    shop.products.add(product);
    product.shops.add(shop);
    product.save();
    return product;
}

10-06 06:21