微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何避免使用 JPA

如何解决如何避免使用 JPA

@Entity
@Table(name = "PERSISTENCE_USER")

    public class User implements Serializable {
        // HERE IS A SNIPPET
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
    
        private Long id;
        @NotNull
        private String firstName;
        @NotNull
        private String lastName;
        ................
    }
@Entity
@Table(name = "PERSISTENCE_ORDER")
@NamedQueries({
    @NamedQuery(
            name = "findAllorders",query = "SELECT o FROM CustomerOrder o"
    ),@NamedQuery(
            name = "deleteall",query = "DELETE FROM CustomerOrder"
    )
})

    public class CustomerOrder implements Serializable {
    
        //HERE IS A SNIPPET
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        @NotNull
        String status;
        @NotNull
        @OnetoMany(cascade = CascadeType.ALL,orphanRemoval = true)
        private List<LineItem> lineItems;
        @NotNull
        @ManyToOne
        private User customer;
        ...........
    }

当我尝试删除与 User 实体具有单向 @ManyToOne 的 CustomerOrder 实体时,出现以下错误

Internal Exception: org.apache.derby.shared.common.error.DerbysqlIntegrityConstraintViolationException: DELETE on table 'PERSISTENCE_ORDER' caused a violation of foreign key constraint 'PRSSTNCSRPRSSRDRSD' for key (21).  The statement has been rolled back.
Error Code: 20000
Call: DELETE FROM PERSISTENCE_ORDER
Query: DeleteallQuery(name="deleteall" referenceClass=CustomerOrder sql="DELETE FROM PERSISTENCE_ORDER")
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:905)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeNoSelect(DatabaseAccessor.java:967)
        ............................................................................
        ............................................................................
Caused by: org.apache.derby.shared.common.error.DerbysqlIntegrityConstraintViolationException: DELETE on table 'PERSISTENCE_ORDER' caused a violation of foreign key constraint 'PRSSTNCSRPRSSRDRSD' for key (21).  The statement has been rolled back.

之后,我尝试先删除 User 实体,然后再删除 CustomerOrder 实体,但这没有任何区别。我应该如何定义实体关系映射以避免此错误

谢谢

PS:我在 Windows 10 64 位和 Apache Derby DB 上使用带有 EclipseLink 的 Glassfish 5.1

解决方法

当发出“DELETE FROM CustomerOrder”批量删除查询时,JPA 不会为您做任何事情 - 它完全按照 JPQL 的要求发出 SQL - 因此由您通过清空或删除任何引用来维护到要删除的行,然后再删除。

异常本身表明违反了 FK 约束“PRSSTNCSRPRRSSRDRSD”,可以在数据库中找到该约束以准确告诉您是哪个关系导致了问题。查看 CustomerOrder 实体,lineItems 集合的映射方式是将外键放入 LineItems 表中,这需要在删除成功之前清除这些行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。