为啥 JPA 的 drop-and-create 选项不起作用

Posted

技术标签:

【中文标题】为啥 JPA 的 drop-and-create 选项不起作用【英文标题】:Why the JPA drop-and-create option is not working为什么 JPA 的 drop-and-create 选项不起作用 【发布时间】:2021-03-01 15:40:33 【问题描述】:

我使用 Apache Derby 作为数据库,EclipseLink JPA 在 Glassfish 5.1 上运行,Netbeans 12.0 作为我的开发环境。我已经解决了好几天的问题,但我似乎没有找到摆脱它的方法。非常感谢任何帮助。

我在persistence.xml 中选择了drop-and-create 选项。我使用 JPA 的生成脚本来执行拖放和创建操作。

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
    <!-- Define Persistence Unit -->
    <persistence-unit name="listserviceDB" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>java:comp/DefaultDataSource</jta-data-source>
        <properties>
            <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
            <property name="javax.persistence.schema-generation.drop-source" value="script"/>
            <property name="javax.persistence.schema-generation.drop-script-source" value="META-INF/drop.sql"/>
            <property name="javax.persistence.schema-generation.create-source" value="script"/>
            <property name="javax.persistence.schema-generation.create-script-source" value="META-INF/create.sql"/>
            <property name="eclipselink.logging.level" value="FINE"/>
            <property name="eclipselink.logging.level.sql" value="FINE"/>
            <property name="eclipselink.logging.parameters" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

放置脚本:

ALTER TABLE PERSISTENCE_LINEITEM DROP CONSTRAINT PRSSTNCLNEITEMPRTD
ALTER TABLE PERSISTENCE_LINEITEM DROP CONSTRAINT PRSSTNCLNITEMLNTMD
ALTER TABLE PERSISTENCE_ORDER DROP CONSTRAINT PRSSTNCORDERCNSMRD
DROP TABLE PERSISTENCE_LINEITEM
DROP TABLE PERSISTENCE_ORDER
DROP TABLE PERSISTENCE_USER
DROP TABLE PERSISTENCE_PART
DELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN'

创建脚本:

CREATE TABLE PERSISTENCE_LINEITEM (ID BIGINT NOT NULL, QUANTITY INTEGER, LINEITEMID BIGINT, PART_ID BIGINT, PRIMARY KEY (ID))
CREATE TABLE PERSISTENCE_ORDER (ID BIGINT NOT NULL, LASTUPDATED TIMESTAMP, ORDERNUMBER VARCHAR(255), STATUS VARCHAR(255), TOTAL FLOAT, CONSUMERID BIGINT, PRIMARY KEY (ID))
CREATE TABLE PERSISTENCE_USER (ID BIGINT NOT NULL, CELLPHONE VARCHAR(255), COMPANY VARCHAR(255), DATEOFBIRTH DATE, EMAIL VARCHAR(255), FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), OFFICEPHONE VARCHAR(255), PASSWORD VARCHAR(255), USERID VARCHAR(255), USERROLE VARCHAR(255), PRIMARY KEY (ID))
CREATE TABLE PERSISTENCE_PART (ID BIGINT NOT NULL, DESCRIPTION VARCHAR(255), MANUFACTURE VARCHAR(255), NAME VARCHAR(255), NUMBER VARCHAR(255), PRICE FLOAT, PRIMARY KEY (ID))
ALTER TABLE PERSISTENCE_LINEITEM ADD CONSTRAINT PRSSTNCLNEITEMPRTD FOREIGN KEY (PART_ID) REFERENCES PERSISTENCE_PART (ID)
ALTER TABLE PERSISTENCE_LINEITEM ADD CONSTRAINT PRSSTNCLNITEMLNTMD FOREIGN KEY (LINEITEMID) REFERENCES PERSISTENCE_ORDER (ID)
ALTER TABLE PERSISTENCE_ORDER ADD CONSTRAINT PRSSTNCORDERCNSMRD FOREIGN KEY (CONSUMERID) REFERENCES PERSISTENCE_USER (ID)
CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))
INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)

在服务器启动时,我使用带有@PostConstruct 注解标记的方法的@Singleton @Startup bean 来使用JAXB 将初始测试数据从XML 文件加载到数据库中。在我向某些实体添加一些映射关系之前,该应用程序可以正常工作。现在,由于服务器启动时的某些原因,JPA 无法删除那些具有映射关系的实体的表,因此,应用程序正在将数据插入到现有的包含数据的表中,这会导致“违反唯一主键约束”异常被抛出。正如 JEE 规范所预期的那样,启动时的任何应用程序异常都会使 bean 中的 CDI 无效(在我的情况下,EntityManager 注入变为 null)并且这会破坏代码。我有实体“Part”、“AppUser”、“CustomerOrder”和“LineItem”。 “Part”实体没有映射关系,因此创建和加载成功,但其余实体有问题。

@Singleton
@Startup
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class DataLoaderSessionBean 
   @PostConstruct
   public void createData() 
      loadParts();
      loadUsers();
  



 @Entity
    @Table(name = "PERSISTENCE_USER")
    public class AppUser implements Serializable 
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @XmlTransient
        private Long id;
        @NotNull
        private String userId;
        @NotNull
        private String password;
        @NotNull
        private String userRole;
        @NotNull
        private String firstName;
        @NotNull
        private String lastName;
        @Temporal(TemporalType.DATE)
        @NotNull
        private Date dateOfBirth;
        @NotNul
        private String officePhone;
        private String cellPhone;
        private String email;
        private String company;
        @OneToMany (mappedBy = "consumer", cascade = CascadeType.ALL)
        private List<CustomerOrder> orders;

        
@Entity
@Table(name = "PERSISTENCE_ORDER")
public class CustomerOrder implements Serializable 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull
    String status;
    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastUpdated;
    @NotNull
    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
    private List<LineItem> lineItems;
    @NotNull
    @JoinColumn(name="CONSUMERID")
    @ManyToOne
    private AppUser consumer;
    @NotNull
    private Double total;
    @NotNull
    private String orderNumber;

@Entity
@Table(name = "PERSISTENCE_LINEITEM")
public class LineItem implements Serializable 
    private static final long serialVersionUID = 1991217202100959L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull
    private Integer quantity;
    @OneToOne
    private Part part;
    @NotNull
    @JoinColumn(name="LINEITEMID")
    @ManyToOne
    private CustomerOrder order;


@Entity
@Table(name = "PERSISTENCE_PART")
public class Part implements Serializable 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull
    private String name;
    @NotNull
    private String manufacture;
    @NotNull
    private String number;
    @NotNull
    private String description;
    @NotNull
    private double price;     

以下是从 XML 文件读取数据并填充用户表的代码 sn-p:

private void loadUsers() 
        List<AppUser> users;
        try 
            JAXBContext context = JAXBContext
                    .newInstance(UserWrapper.class);
            Unmarshaller um = context.createUnmarshaller();
            //  InputStream input = DataLoaderSessionBean.class.getResourceAsStream(partPath);
            UserWrapper warpper = (UserWrapper) um.unmarshal(new File(userPath));
            users = warpper.getUsers();
            List<CustomerOrder> orders = getOrders(users.get(0));
            if (users != null) 
                logger.log(Level.INFO, "Total users loaded by JAXB: 0", users.size());
                users
                        .stream()
                        .forEach(e->e.setOrders(orders));
                requestLogin.addUsers(users);
             else 
                logger.log(Level.SEVERE, "Error: No users were loaded. The 0 file is emply, please check the file", userPath);
            

         catch (JAXBException e) 
            logger.log(Level.SEVERE, "Error: There was a problem reading the data from 0 file. Exception message 1",
                    new Object[]userPath, e.getMessage());
           
        
    
private List<CustomerOrder> getOrders(AppUser u)
        List<CustomerOrder> orders = new ArrayList();
        CustomerOrder order = new CustomerOrder();
        //Creating LineItem
        Part part = requestPart.getPartByNumber("BC774091HA");
        LineItem line = new LineItem(part,2);
        double total = part.getPrice() * line.getQuantity();
        line.setOrder(order);
        List<LineItem> items = new ArrayList();
        items.add(line);
        order.setStatus("Pending Shipment");
        order.setLastUpdated(new Date());
        order.setLineItems(items);
        order.setTotal(total);
        order.setOrderNumber("OTTaviano234576907");
        order.setConsumer(u);
        orders.add(order);
        return orders;
    


public void addUsers(List<AppUser> users) 
        users
                .stream()
                .forEach(this::addUser);
    

    public void addUser(AppUser u) 
     //   public void addUser(AppUser u) throws ListServiceException 
        try 
            if (em != null) 
                if (em.isOpen()) 
                    if (u != null) 
                        logger.log(Level.FINEST, "User information to add: id 0 first 1 last 2 dob 3 phone 4",
                                new Object[]u.getUserId(), u.getFirstName(), u.getLastName(),
                                    u.getDateOfBirth(), u.getOfficePhone());
                        em.persist(u);
                        logger.log(Level.FINEST, "The user with id 0 added successfuly",
                                u.getUserId());
                     else 
                        logger.severe("NULL user can not be added");
                    
                 else 
                    logger.severe("Entity manager is closed, user cannot be added");
                
             else 
                logger.severe("EntityManager is NULL, user cannot be added");
            
         catch (Exception e) 
            logger.log(Level.SEVERE, "Tony: Exception while adding user. Error msg 0", e.getMessage());
            throw ThrowListServiceException.wrapException(e);
        
    

日志文件中的sn-p按时间顺序排列:

 Connected: jdbc:derby://localhost:1527/sun-appserv-samples;;create=true
    User: APP
    Database: Apache Derby  Version: 10.14.2.0 - (1828579)
    Driver: Apache Derby Network Client JDBC Driver  Version: 10.14.2.0 - (1828579)]]
.....
ALTER TABLE PERSISTENCE_LINEITEM DROP CONSTRAINT PRSSTNCLNEITEMPRTD]]

ALTER TABLE PERSISTENCE_LINEITEM DROP CONSTRAINT PRSSTNCLNITEMLNTMD]]
  
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: ALTER TABLE failed. There is no constraint 'APP.PRSSTNCLNITEMLNTMD' on table '"APP"."PERSISTENCE_LINEITEM"'. 
Error Code: 30000
Call: ALTER TABLE PERSISTENCE_LINEITEM DROP CONSTRAINT PRSSTNCLNITEMLNTMD
Query: DataModifyQuery(sql="ALTER TABLE PERSISTENCE_LINEITEM DROP CONSTRAINT PRSSTNCLNITEMLNTMD")
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
Caused by: java.sql.SQLSyntaxErrorException: ALTER TABLE failed. There is no constraint 'APP.PRSSTNCLNITEMLNTMD' on table '"APP"."PERSISTENCE_LINEITEM"'. 
Caused by: ERROR 42X86: ALTER TABLE failed. There is no constraint 'APP.PRSSTNCLNITEMLNTMD' on table '"APP"."PERSISTENCE_LINEITEM"'. 
.......
  ALTER TABLE PERSISTENCE_ORDER DROP CONSTRAINT PRSSTNCORDERCNSMRD]]
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: ALTER TABLE failed. There is no constraint 'APP.PRSSTNCORDERCNSMRD' on table '"APP"."PERSISTENCE_ORDER"'. 
Error Code: 30000
Call: ALTER TABLE PERSISTENCE_ORDER DROP CONSTRAINT PRSSTNCORDERCNSMRD
Query: DataModifyQuery(sql="ALTER TABLE PERSISTENCE_ORDER DROP CONSTRAINT PRSSTNCORDERCNSMRD")
Caused by: java.sql.SQLSyntaxErrorException: ALTER TABLE failed. There is no constraint 'APP.PRSSTNCORDERCNSMRD' on table '"APP"."PERSISTENCE_ORDER"'. 
Caused by: ERROR 42X86: ALTER TABLE failed. There is no constraint 'APP.PRSSTNCORDERCNSMRD' on table '"APP"."PERSISTENCE_ORDER"'. 
.....
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210226155716540' because CONSTRAINT 'PRSSTNCRDRPRLNTMSD' is dependent on that object.
Error Code: 30000
Call: DROP TABLE PERSISTENCE_LINEITEM
Query: DataModifyQuery(sql="DROP TABLE PERSISTENCE_LINEITEM")
Caused by: java.sql.SQLTransactionRollbackException: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210226155716540' because CONSTRAINT 'PRSSTNCRDRPRLNTMSD' is dependent on that object.
Caused by: ERROR X0Y25: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210226155716540' because CONSTRAINT 'PRSSTNCRDRPRLNTMSD' is dependent on that object.
.....
DROP TABLE PERSISTENCE_ORDER]]
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210223101327490' because CONSTRAINT 'PRSSTNCRDCSTMRRDRD' is dependent on that object.
Error Code: 30000
Call: DROP TABLE PERSISTENCE_ORDER
Query: DataModifyQuery(sql="DROP TABLE PERSISTENCE_ORDER")
Caused by: java.sql.SQLTransactionRollbackException: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210223101327490' because CONSTRAINT 'PRSSTNCRDCSTMRRDRD' is dependent on that object.
Caused by: ERROR X0Y25: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210223101327490' because CONSTRAINT 'PRSSTNCRDCSTMRRDRD' is dependent on that object.
......
DROP TABLE PERSISTENCE_USER]]
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210223101327520' because CONSTRAINT 'PRSSTNCSRPRSSTNSRD' is dependent on that object.
Error Code: 30000
Call: DROP TABLE PERSISTENCE_USER
Query: DataModifyQuery(sql="DROP TABLE PERSISTENCE_USER")
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
Caused by: java.sql.SQLTransactionRollbackException: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210223101327520' because CONSTRAINT 'PRSSTNCSRPRSSTNSRD' is dependent on that object.
Caused by: ERROR X0Y25: Operation 'DROP CONSTRAINT' cannot be performed on object 'SQL210223101327520' because CONSTRAINT 'PRSSTNCSRPRSSTNSRD' is dependent on that object.
....
DROP TABLE PERSISTENCE_PART]]
DELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN']]
CREATE TABLE PERSISTENCE_LINEITEM (ID BIGINT NOT NULL, QUANTITY INTEGER, LINEITEMID BIGINT, PART_ID BIGINT, PRIMARY KEY (ID))]]
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: Table/View 'PERSISTENCE_LINEITEM' already exists in Schema 'APP'.
Error Code: 30000
Call: CREATE TABLE PERSISTENCE_LINEITEM (ID BIGINT NOT NULL, QUANTITY INTEGER, LINEITEMID BIGINT, PART_ID BIGINT, PRIMARY KEY (ID))
Query: DataModifyQuery(sql="CREATE TABLE PERSISTENCE_LINEITEM (ID BIGINT NOT NULL, QUANTITY INTEGER, LINEITEMID BIGINT, PART_ID BIGINT, PRIMARY KEY (ID))")
Caused by: java.sql.SQLTransactionRollbackException: Table/View 'PERSISTENCE_LINEITEM' already exists in Schema 'APP'.
Caused by: ERROR X0Y32: Table/View 'PERSISTENCE_LINEITEM' already exists in Schema 'APP'.
.....
CREATE TABLE PERSISTENCE_ORDER (ID BIGINT NOT NULL, LASTUPDATED TIMESTAMP, ORDERNUMBER VARCHAR(255), STATUS VARCHAR(255), TOTAL FLOAT, CONSUMERID BIGINT, PRIMARY KEY (ID))]]  
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: Table/View 'PERSISTENCE_ORDER' already exists in Schema 'APP'.
Error Code: 30000
Call: CREATE TABLE PERSISTENCE_ORDER (ID BIGINT NOT NULL, LASTUPDATED TIMESTAMP, ORDERNUMBER VARCHAR(255), STATUS VARCHAR(255), TOTAL FLOAT, CONSUMERID BIGINT, PRIMARY KEY (ID))
Query: DataModifyQuery(sql="CREATE TABLE PERSISTENCE_ORDER (ID BIGINT NOT NULL, LASTUPDATED TIMESTAMP, ORDERNUMBER VARCHAR(255), STATUS VARCHAR(255), TOTAL FLOAT, CONSUMERID BIGINT, PRIMARY KEY (ID))")
Caused by: java.sql.SQLTransactionRollbackException: Table/View 'PERSISTENCE_ORDER' already exists in Schema 'APP'.
Caused by: ERROR X0Y32: Table/View 'PERSISTENCE_ORDER' already exists in Schema 'APP'.
.....
CREATE TABLE PERSISTENCE_USER (ID BIGINT NOT NULL, CELLPHONE VARCHAR(255), COMPANY VARCHAR(255), DATEOFBIRTH DATE, EMAIL VARCHAR(255), FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), OFFICEPHONE VARCHAR(255), PASSWORD VARCHAR(255), USERID VARCHAR(255), USERROLE VARCHAR(255), PRIMARY KEY (ID))]]
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: Table/View 'PERSISTENCE_USER' already exists in Schema 'APP'.
Error Code: 30000
Call: CREATE TABLE PERSISTENCE_USER (ID BIGINT NOT NULL, CELLPHONE VARCHAR(255), COMPANY VARCHAR(255), DATEOFBIRTH DATE, EMAIL VARCHAR(255), FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), OFFICEPHONE VARCHAR(255), PASSWORD VARCHAR(255), USERID VARCHAR(255), USERROLE VARCHAR(255), PRIMARY KEY (ID))
Query: DataModifyQuery(sql="CREATE TABLE PERSISTENCE_USER (ID BIGINT NOT NULL, CELLPHONE VARCHAR(255), COMPANY VARCHAR(255), DATEOFBIRTH DATE, EMAIL VARCHAR(255), FIRSTNAME VARCHAR(255), LASTNAME VARCHAR(255), OFFICEPHONE VARCHAR(255), PASSWORD VARCHAR(255), USERID VARCHAR(255), USERROLE VARCHAR(255), PRIMARY KEY (ID))")
Caused by: java.sql.SQLTransactionRollbackException: Table/View 'PERSISTENCE_USER' already exists in Schema 'APP'.
Caused by: ERROR X0Y32: Table/View 'PERSISTENCE_USER' already exists in Schema 'APP'.
......
CREATE TABLE PERSISTENCE_PART (ID BIGINT NOT NULL, DESCRIPTION VARCHAR(255), MANUFACTURE VARCHAR(255), NAME VARCHAR(255), NUMBER VARCHAR(255), PRICE FLOAT, PRIMARY KEY (ID))]]
ALTER TABLE PERSISTENCE_LINEITEM ADD CONSTRAINT PRSSTNCLNEITEMPRTD FOREIGN KEY (PART_ID) REFERENCES PERSISTENCE_PART (ID)]]
ALTER TABLE PERSISTENCE_LINEITEM ADD CONSTRAINT PRSSTNCLNITEMLNTMD FOREIGN KEY (LINEITEMID) REFERENCES PERSISTENCE_ORDER (ID)]]
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'LINEITEMID' is not a column in table or VTI 'PERSISTENCE_LINEITEM'.
Error Code: 30000
Call: ALTER TABLE PERSISTENCE_LINEITEM ADD CONSTRAINT PRSSTNCLNITEMLNTMD FOREIGN KEY (LINEITEMID) REFERENCES PERSISTENCE_ORDER (ID)
Query: DataModifyQuery(sql="ALTER TABLE PERSISTENCE_LINEITEM ADD CONSTRAINT PRSSTNCLNITEMLNTMD FOREIGN KEY (LINEITEMID) REFERENCES PERSISTENCE_ORDER (ID)")
Caused by: java.sql.SQLSyntaxErrorException: 'LINEITEMID' is not a column in table or VTI 'PERSISTENCE_LINEITEM'.
Caused by: ERROR 42X14: 'LINEITEMID' is not a column in table or VTI 'PERSISTENCE_LINEITEM'.
......
ALTER TABLE PERSISTENCE_ORDER ADD CONSTRAINT PRSSTNCORDERCNSMRD FOREIGN KEY (CONSUMERID) REFERENCES PERSISTENCE_USER (ID)]]  
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: 'CONSUMERID' is not a column in table or VTI 'PERSISTENCE_ORDER'.
Error Code: 30000
Call: ALTER TABLE PERSISTENCE_ORDER ADD CONSTRAINT PRSSTNCORDERCNSMRD FOREIGN KEY (CONSUMERID) REFERENCES PERSISTENCE_USER (ID)
Query: DataModifyQuery(sql="ALTER TABLE PERSISTENCE_ORDER ADD CONSTRAINT PRSSTNCORDERCNSMRD FOREIGN KEY (CONSUMERID) REFERENCES PERSISTENCE_USER (ID)")
Caused by: java.sql.SQLSyntaxErrorException: 'CONSUMERID' is not a column in table or VTI 'PERSISTENCE_ORDER'.
Caused by: ERROR 42X14: 'CONSUMERID' is not a column in table or VTI 'PERSISTENCE_ORDER'.
......
CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))]]
Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLTransactionRollbackException: Table/View 'SEQUENCE' already exists in Schema 'APP'.
Error Code: 30000
Call: CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))
Query: DataModifyQuery(sql="CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))")
Caused by: java.sql.SQLTransactionRollbackException: Table/View 'SEQUENCE' already exists in Schema 'APP'.
Caused by: ERROR X0Y32: Table/View 'SEQUENCE' already exists in Schema 'APP'.
......
  INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)
  Total records loaded into Part Table successfuly by JAXB: 19
.....
INSERT INTO PERSISTENCE_USER (ID, CELLPHONE, COMPANY, DATEOFBIRTH, EMAIL, FIRSTNAME, LASTNAME, OFFICEPHONE, PASSWORD, USERID, USERROLE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    bind => [20, (917)-971-6854, Leman Brothers, 2020-12-29, null, Joseph, Ottaviano, (718)-815-8111, admin, admin, superadmin]]]

Local Exception Stack: 
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.apache.derby.shared.common.error.DerbySQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL210223101327520' defined on 'PERSISTENCE_USER'.
Error Code: 20000
Call: INSERT INTO PERSISTENCE_USER (ID, CELLPHONE, COMPANY, DATEOFBIRTH, EMAIL, FIRSTNAME, LASTNAME, OFFICEPHONE, PASSWORD, USERID, USERROLE) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    bind => [20, (917)-971-6854, Leman Brothers, 2020-12-29, null, Joseph, Ottaviano, (718)-815-8111, admin, admin, superadmin]
Query: InsertObjectQuery(org.me.mavenlistservicedb.entity.AppUser@65038c6d)
Caused by: org.apache.derby.shared.common.error.DerbySQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL210223101327520' defined on 'PERSISTENCE_USER'.
Caused by: ERROR 23505: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL210223101327520' defined on 'PERSISTENCE_USER'.

知道为什么这些表没有被删除吗?

提前致谢

【问题讨论】:

“在服务器启动期间,JPA 在删除表之前创建数据” - 究竟如何?这是需要更多细节的东西,因为 EclipseLink 不能也没有控制此设置中的数据输入 - 您的应用程序是。另请注意,当您将 Native EclipseLink 属性与 JPA 属性混合和匹配时,我认为您没有使用所有适当的 DDL 参数。请参阅***.com/a/66317425/496099,因为我怀疑 DDL 没有发生 - glassfish 可能不尊重甚至看到 EclipseLink 属性。 打开 EclipseLink 日志记录:wiki.eclipse.org/EclipseLink/Examples/JPA/Logging(也可以通过 glassfish 日志记录选项控制),它将显示它发出的 SQL。 loadUsers 代码肯定有问题,因为我不知道会违反什么约束 - 你有 ID 生成,所以它们不会重复,除非你在不同的 EntityManager 上下文中对同一个实体调用 persist 两次。 谢谢 Chris,我会这样做的,我还将包含将数据加载到表中的代码。 您必须检查数据库以找出阻止两个现有表被删除的约束 PRSSTNCRDCSTMRRRDD 和 PRSSTNCSRPRSSTNSRD 是什么。我不知道它们是如何添加的或它们是什么,但您可能需要自己手动删除它们,或者生成一个 DDL 放置表脚本,然后让 EclipseLink 使用它——使用放置脚本可以让您修复放置如果有办法强制它运行,或者查询和删除 JPA 不知道的约束,则使用 table 语句。 克里斯,感谢所有的指点。我使用了 JPA 生成的 drop 和 create 脚本,并用日志摘要更新了我的帖子。我不确定为什么不能删除这些约束? 【参考方案1】:

问题与 Netbeans IDE 中的数据库配置有关。从 Services->Database->Java DB 我将属性更改为指向我系统中的 Derby 安装,而不是嵌入 Glassfish 的那个。我杀死了正在侦听端口 1527(特定于 derby)的进程。我重新启动了 IDE、数据库服务器,应用程序运行良好(几乎没问题)。

【讨论】:

以上是关于为啥 JPA 的 drop-and-create 选项不起作用的主要内容,如果未能解决你的问题,请参考以下文章

JPA 为啥使用 createNamedQuery

为啥flyway迁移需要JPA依赖才能运行

您将哪种 Java 类型用于 JPA 集合,为啥?

为啥在看到 PersistentBag 的实体中使用 JPA 列出(@OneToMany)

Spring\JPA\PostgreSQL:为啥我得到一个不是我创建的表?

为啥 Google App Engine 文档强调 JDO 而不是 JPA?