使用play-framework 2.2.x删除对象时违反参照完整性约束

时间:2013-11-27 20:11:32

标签: java jpa playframework-2.0 h2 ebean

我设计了我的数据库,以便我可以访问购买列表(历史记录)以及最新购买的简单外键链接。除了我尝试删除客户时,一切(基本的crud操作)都有效。我已经创建了一个小样本项目来举例说明我遇到的问题,我已经在演示ebean project之后进行了建模。

完整的代码发布在github

引用的单元测试(以及任何删除)会引发以下异常:

参照完整性约束违规:“FK_CUSTOMER_LATESTPURCHASE_1:PUBLIC.CUSTOMER FOREIGN KEY(LATEST_PURCHASE_ID)参考PUBLIC.PURCHASE(ID)(2)”; SQL语句:从购买中删除customer_id =?

Full Stack Trace here

代码

Customer Model

package models;


@Entity
public class Customer extends Model {
    // Modeled after https://github.com/ebean-orm-demo/demo-order/blob/master/src/main/java/app/data/Customer.java#L48-L49
    @Id
    private Long id;
    private String name;
    private boolean valid;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
    private List<Purchase> purchases;
    @ManyToOne
    private Purchase latestPurchase;


    public void addOrder(Purchase purchase) {
        this.purchases.add(purchase);
        this.setLatestPurchase(purchase);
        purchase.setCustomer(this);
        purchase.save();
    }

    .. standard getters and setters ..
}

Purchase Model

包装模型;

@Entity
public class Purchase extends Model {

    @Id
    private Long id;
    private String name;
    @ManyToOne
    @JoinColumn(name="customer_id")
    private Customer customer;

    .. standard getters and setters ..
}

Unit Test that fails

@Test
public void deleteCustomerCascades() {
    running(fakeApplication(), new Runnable() {
        public void run() {
            Customer randy = new Customer("Randy Marsh");
            randy.save();
            // Let's add some purchases for randy
            randy.addOrder(new Purchase("PS4"));
            randy.addOrder(new Purchase("XBOX One Bundulru"));
            //persist
            randy.update();

            Customer retrieved = Customer.find.byId(randy.getId());

            assertThat(retrieved.getLatestPurchase().getName()).isEqualTo("XBOX One Bundulru");
            assertNotNull(retrieved.getId());
            assertEquals(retrieved.getLatestPurchase().getName(),"XBOX One Bundulru");
            // There are 2 total purchases
            assertEquals(Purchase.find.all().size(), 2);
            // And Randy has two.
            assertEquals(retrieved.getPurchases().size(),2);
            // Randy is the owner of both purchases
            assertEquals(randy.getLatestPurchase().getCustomer(),randy);
            for (Purchase purchase : Purchase.find.all()){
                assertEquals(purchase.getCustomer().getName(),"Randy Marsh");
            }
            // Let's delete the customer, and his purchases with it
            retrieved.delete();
            retrieved.update();
            assertThat(Purchase.find.all().size()).isEqualTo(0);
        }
    });
}

1 个答案:

答案 0 :(得分:1)

您忘记将orphanRemoval=true添加到OneToMany关系中。此外,我认为在retrieved之后更新retrieved.update()时,您会收到另一个例外。