无法添加或更新子行:hibernate中的外键约束失败

时间:2015-02-13 11:37:31

标签: java mysql hibernate jpa

我正在使用JPA,Hibernate和MySQL

我正在追踪异常

  

无法添加或更新子行:外键约束失败

@Entity
@Table(name = "my_payment_request")
public class Request implements Serializable {
     private static final long serialVersionUID = 1L;

     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     private Long id;

     @OneToMany(mappedBy = "request",cascade=CascadeType.ALL)
     private List<PaymentItem> paymentItems;

}

@Entity
@Table(name = "my_payment_item")
public class PaymentItem {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ManyToOne
    @JoinColumn(name = "request_id", nullable=true)
    private Request request;

}

public class Manager {
Request request = new Request();
    List<PaymentItem> paymentItems = new ArrayList<PaymentItem>();
        PaymentItem paymentItem1 = new PaymentItem();
        paymentItem1.setRequest(request);
        PaymentItem paymentItem2 = new PaymentItem();
        paymentItem2.setRequest(request);
        paymentItems.add(paymentItem1);
        paymentItems.add(paymentItem2);
        request.setPaymentItems(paymentItems);

}
  

Hibernate代码

Session session = sessionFactory.openSession();
        session.beginTransaction();

        request.setId((Long) session.save(request));
        session.getTransaction().commit();

1 个答案:

答案 0 :(得分:-2)

在插入命令之前添加此项来关闭它:

SET foreign_key_checks = 0;

然后在插入后将其设置回来:

SET foreign_key_checks = 1;

确保你知道自己在做什么。