Hibernate外键约束失败

时间:2014-07-04 13:46:35

标签: java mysql hibernate

我想创建名为客户订单的SQL数据库表 SQL:

CREATE TABLE Customer (
  customer_id INT NOT NULL AUTO_INCREMENT,
  customer_name VARCHAR(255) UNIQUE,
  PRIMARY KEY (customer_id)
);


CREATE TABLE Orders (
  order_id INT NOT NULL AUTO_INCREMENT,
  customer_name VARCHAR(255),
  order_date DATETIME,
  PRIMARY KEY(order_id),
  FOREIGN KEY (customer_name) REFERENCES Customer(customer_name)
  ON UPDATE CASCADE
  ON DELETE CASCADE
);

之后我想插入一个带有Customer对象引用的Orders对象。 Java&休眠:

Transaction tx = session.beginTransaction();
Customer cu = (Customer) session.load(Customer.class, 1);

Date d = new Date();
Orders od = new Orders(cu, d);
od.setCustomer(cu);

Set<Orders> hs = new HashSet<Orders>();
hs.add(od);
cu.setOrderses(hs);

 session.save(cu);
 session.save(od);
 tx.commit();

插入返回异常: 无法添加或更新子行:外键约束失败 我正在完成与Hibernate教程完全相同的一切。 我做错了什么?

Java类

    public class Customer  implements java.io.Serializable {


     private Integer customerId;
     private String customerName;
     private Set<Orders> orderses = new HashSet<Orders>(0);

    public Customer() {
    }

    public Customer(String customerName, Set<Orders> orderses) {
       this.customerName = customerName;
       this.orderses = orderses;
    }

    public Integer getCustomerId() {
        return this.customerId;
    }

    public void setCustomerId(Integer customerId) {
        this.customerId = customerId;
    }
    public String getCustomerName() {
        return this.customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }
    public Set<Orders> getOrderses() {
        return this.orderses;
    }

    public void setOrderses(Set<Orders> orderses) {
        this.orderses = orderses;
    }

}

    public class Orders  implements java.io.Serializable {


     private Integer orderId;
     private Customer customer;
     private Date orderDate;

    public Orders() {
    }

    public Orders(Customer customer, Date orderDate) {
       this.customer = customer;
       this.orderDate = orderDate;
    }

    public Integer getOrderId() {
        return this.orderId;
    }

    public void setOrderId(Integer orderId) {
        this.orderId = orderId;
    }
    public Customer getCustomer() {
        return this.customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }
    public Date getOrderDate() {
        return this.orderDate;
    }

    public void setOrderDate(Date orderDate) {
        this.orderDate = orderDate;
    }

}

1 个答案:

答案 0 :(得分:0)