문제

I have 2 entity Shop and Product having many-to-many relation and PlayFramework created a table product_shop which stores shop_id ,product_id but everytime when I am adding a new product the previous product_id row is deleted and new one is stored in product_shop table.

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;
    }     
}
도움이 되었습니까?

해결책

The problem is in 'create' method in Product class.
This method creates new list and adds a product to it. Then it assigns this list to shop.
Doing this it overrides previous list of products. To solve this problem all we have to is changing 'create' method to following:

public static Product create(Product product,Shop shop) {      
    shop.products.add(product);
    product.shops.add(shop);
    product.save();
    return product;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top