MySQLIntegrityConstraintViolationException:无法添加或更新子行

时间:2014-04-26 19:36:57

标签: java foreign-keys playframework-2.2

我的观点add.scala.html就是这个 enter image description here

所以,如果我添加一个产品,它显示在同一个屏幕上,我有一个删除按钮删除product.My问题是,当我添加新产品,它工作正常,但当我删除任何一个后添加一个新产品,然后它给出我的错误

[PersistenceException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`shopdb`.`product_shop`, CONSTRAINT `fk_product_shop_product_01` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`))]

在我的models.Product.java

public static Product create(Product product,Shop shop) {
        product.save();

    static   List<Product> products = new ArrayList<>();
        products.add(product);

        shop.products = products;
       shop.save();//getting error on this line




        return product;
    }
    public static void delete(Long id) {
        find.ref(id).delete();
    }

我的数据库

create table product (
  id                        bigint auto_increment not null,
  name                      varchar(255),
  price                     float,
  category                  varchar(255),
  constraint pk_product primary key (id))
;

create table shop (
  id                        bigint auto_increment not null,
  name                      varchar(255),
  address_line1             varchar(255),
  address_line2             varchar(255),
  address_line3             varchar(255),
  city                      varchar(255),
  town                      varchar(255),
  phone_number              varchar(255),
  category                  varchar(255),
  shop_pic                  longblob,
  owner_id                  bigint,
  constraint pk_shop primary key (id))
;

create table product_shop (
  product_id                     bigint not null,
  shop_id                        bigint not null,
  constraint pk_product_shop primary key (product_id, shop_id))
;

alter table product_shop add constraint fk_product_shop_product_01 foreign key (product_id) references product (id) on delete restrict on update restrict;

alter table product_shop add constraint fk_product_shop_shop_02 foreign key (shop_id) references shop (id) on delete restrict on update restrict;

任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:0)

你为什么要分配

shop.products = products;

不应该这样做

shop.products.add(products); ?