简体   繁体   English

EntityManager刷新时,JPA外键约束失败

[英]JPA Foreign Key Constraint Fails on EntityManager flush

I've been following the NetBeans AffableBean e-commerce tutorial, but using IntelliJ as my IDE instead. 我一直在关注NetBeans AffableBean电子商务教程,但是使用IntelliJ作为我的IDE。 I have gotten everything working up until the point where I need to add Customers to the database, as well as a CustomerOrder relating to the order they are placing. 我已经完成了所有工作,直到需要将客户添加到数据库以及与客户所下订单有关的CustomerOrder为止。 The section of the tutorial is visible here: 教程的部分在这里可见:

https://netbeans.org/kb/docs/javaee/ecommerce/transaction.html#placeOrder https://netbeans.org/kb/docs/javaee/ecommerce/transaction.html#placeOrder

When I place an order, I receive the following error: 下订单时,出现以下错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`larrys`.`customer_order`, CONSTRAINT `fk_customer_order_customer` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

When flushing the EntityManager here: 在此处刷新EntityManager时:

private void addOrderedItems(CustomerOrder order, ShoppingCart cart) {

    em.flush(); //Here

    List<ShoppingCartItem> items = cart.getItems();

    for (ShoppingCartItem scItem : items) {

        int productId = scItem.getProduct().getId();

        OrderedProductPK orderedProductPK = new OrderedProductPK();
        orderedProductPK.setCustomerOrderId(order.getId());
        orderedProductPK.setProductId(productId);

        OrderedProduct orderedItem = new OrderedProduct(orderedProductPK);

        orderedItem.setQuantity(scItem.getQuantity());

        em.persist(orderedItem);
    }
}

My full OrderManager code is visible here: 我的完整OrderManager代码在这里可见:

http://pastebin.com/jRintrTS

Please correct me otherwise, but from what I can understand about the error, I am trying to insert a row in the customer_order table but cannot do this as the foreign key reference to customer_id does not exist in the customer table. 否则,请纠正我,但是据我对错误的了解,我正在尝试在customer_order表中插入一行,但是不能这样做,因为对customer_id的外键引用在customer表中不存在。 However, I have created the customer and persisted it before the order, so I don't understand why it isn't committing the data to the database before attempting to create a CustomerOrder. 但是,我已经创建了客户并将其保留在订单之前,因此我不明白为什么它在尝试创建CustomerOrder之前不将数据提交到数据库。

This is the schema sql provided by netbeans for the e-commerce project: 这是netbeans为电子商务项目提供的模式sql:

https://netbeans.org/projects/samples/sources/samples-source-code/content/samples/javaee/AffableBean/setup/schemaCreation.sql https://netbeans.org/projects/samples/sources/samples-source-code/content/samples/javaee/AffableBean/setup/schemaCreation.sql

And my persistence.xml file, identical to the one provided in the tutorial: 还有我的persistence.xml文件,与教程中提供的文件相同:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">

    <persistence-unit name="LarrysPU" transaction-type="JTA">
        <jta-data-source>jdbc/larrys</jta-data-source>
        <properties/>
    </persistence-unit>
</persistence>

The only thing different about my project and the NetBeans project is that in my customer table, I have changed cityRegion to town , added postcode and county , and my project uses a different name to AffableBean. 我的项目和NetBeans项目的唯一不同之处在于,在customer表中,我将cityRegion更改为town ,添加了postcodecounty ,并且我的项目使用了与AffableBean不同的名称。

Has anyone got any ideas as to where I might be going wrong? 有人对我可能会出错的地方有任何想法吗?

EDIT - GlassFish Log when encountering the error: 编辑-遇到错误时,GlassFish日志:

[2015-06-11T21:18:57.799+0100] [glassfish 4.1] [FINE] [] [org.eclipse.persistence.session.file:/OBFUSCATED/Larrys/out/artifacts/Larrys/WEB-INF/classes/_LarrysPU.sql] [tid: _ThreadID=26 _ThreadName=http-listener-1(2)] [timeMillis: 1434053937799] [levelValue: 500] [[
  INSERT INTO larrys.customer (id, address, cc_number, county, email, name, phone, postcode, town) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    bind => [9 parameters bound]]]

[2015-06-11T21:18:57.800+0100] [glassfish 4.1] [FINEST] [] [org.eclipse.persistence.session.file:/OBFUSCATED/Larrys/out/artifacts/Larrys/WEB-INF/classes/_LarrysPU.query] [tid: _ThreadID=26 _ThreadName=http-listener-1(2)] [timeMillis: 1434053937800] [levelValue: 300] [[
  Execute query InsertObjectQuery(entity.CustomerOrder@1f3cec0)]]

[2015-06-11T21:18:57.801+0100] [glassfish 4.1] [FINE] [] [org.eclipse.persistence.session.file:/OBFUSCATED/Larrys/out/artifacts/Larrys/WEB-INF/classes/_LarrysPU.sql] [tid: _ThreadID=26 _ThreadName=http-listener-1(2)] [timeMillis: 1434053937801] [levelValue: 500] [[
  INSERT INTO larrys.customer_order (id, amount, confirmation_number, date_created, customer_id) VALUES (?, ?, ?, ?, ?)
    bind => [5 parameters bound]]]

[2015-06-11T21:18:57.802+0100] [glassfish 4.1] [FINE] [] [org.eclipse.persistence.session.file:/OBFUSCATED/Larrys/out/artifacts/Larrys/WEB-INF/classes/_LarrysPU.sql] [tid: _ThreadID=26 _ThreadName=http-listener-1(2)] [timeMillis: 1434053937802] [levelValue: 500] [[
  SELECT 1]]

[2015-06-11T21:18:57.802+0100] [glassfish 4.1] [WARNING] [] [org.eclipse.persistence.session.file:/OBFUSCATED/Larrys/out/artifacts/Larrys/WEB-INF/classes/_LarrysPU] [tid: _ThreadID=26 _ThreadName=http-listener-1(2)] [timeMillis: 1434053937802] [levelValue: 900] [[

Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`larrys`.`customer_order`, CONSTRAINT `fk_customer_order_customer` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Error Code: 1452

It turns out that the issue I encountered was caused by the fact my Id accessors had no @GeneratedValue(strategy = GenerationType.IDENTITY) , so I added this for each Entity. 原来,我遇到的问题是由于我的ID访问器没有@GeneratedValue(strategy = GenerationType.IDENTITY)导致的,因此我为每个Entity都添加了这个问题。

As for fixing the Unknown column 'SOMETHING' in 'field list' error I received, it turns out I only received this for the OrderedProduct class. 至于解决我收到的Unknown column 'SOMETHING' in 'field list'错误,事实证明我只为OrderedProduct类收到了此消息。 Instead of using the @Annotations on fields, I chose to use them on their accessor methods, which could allow for customization in the future; 我选择在它们的访问器方法上使用它们,而不是在字段上使用@Annotations,这可能会在将来进行自定义; but I forgot about this: 但是我忘记了这一点:

@EmbeddedId
protected OrderedProductPK orderedProductPK;

where the @EmbeddedId annotation should have been present on an accessor for the OrderedProductPK. @EmbeddedId批注在OrderedProductPK的访问器上应该已经存在的位置。

I'm guessing there is a customerId property on OrderedProduct and you need to call orderedItem.setCustomerId() or orderedItem.setCustomer() with a valid customer id or valid customer object depending on how you've created the entity classes. 我猜想OrderedProduct上有一个customerId属性,您需要根据创建实体类的方式使用有效的客户ID或有效的客户对象来调用orderedItem.setCustomerId()或orderedItem.setCustomer()。 These seem to be the only two lines that set values on the orderedItem object. 这些似乎是在orderedItem对象上设置值的仅有的两行。

// order id
orderedProductPK.setCustomerOrderId(order.getId());
// product id
orderedProductPK.setProductId(productId);
// object created with order and product associations
OrderedProduct orderedItem = new OrderedProduct(orderedProductPK);
// quantity set
orderedItem.setQuantity(scItem.getQuantity());
// customer is not associated

A customer needs to be associated with the orderedItem. 客户需要与orderedItem相关联。

EDIT: Looking at the tutorial it looks like customer is associated with the order object. 编辑:看教程,看起来客户与订单对象相关联。 What do you get for order.getCustomer()? 您会获得什么order.getCustomer()? If it is null, that's your problem. 如果为null,那就是您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM