gpt4 book ai didi

java - 不创建或检索 JPA 条目

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:55 25 4
gpt4 key购买 nike

我正在使用实体管理器创建 JPA 条目的程序。在此过程中,我没有收到任何错误

...
factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();

entityManager.getTransaction().begin();
entityManager.persist(object);
entityManager.getTransaction().commit();

...

entityManager.close();

我创建了一个如下的程序来读取数据,但它不返回任何数据,查询返回空。可能是什么原因?

这是读取数据的程序:

static List<String> classList = new ArrayList<String>();
private static EntityManagerFactory factory;

public static void main(String[] args) {
// TODO Auto-generated method stub

factory = Persistence.createEntityManagerFactory("perst");
EntityManager entityManager = factory.createEntityManager();

classList.add("LeaveRequest");
classList.add("person");

for (Object classOjc : classList) {

String className = classOjc.toString();

Query query = entityManager.createQuery("SELECT p FROM " + className + " p");

@SuppressWarnings("rawtypes")
List resultList = query.getResultList();

System.out.println(resultList.size());

for (Object result : resultList) {

System.out.println(result.toString());
}
}
}

xml 持久化为:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">


<persistence-unit name="perst" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>LeaveRequest</class>
<class>person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:derby:/home/vogella/databases/simpleDb;create=true" />
<property name="javax.persistence.jdbc.user" value="Sales" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
<property name="eclipselink.logging.level" value="SEVERE" />
<property name="eclipselink.logging.exceptions" value="true" />
</properties>
</persistence-unit>
</persistence>

最佳答案

您将 eclipselink 配置为在每次启动应用程序时删除并重新创建架构:

<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />

很明显,如果您运行第一个应用程序来保留一些条目,然后运行第二个应用程序尝试读取第一个应用程序所写入的内容,那么您将找不到任何内容,因为 eclipselink 每次都会删除所有内容并重新创建架构。

关于java - 不创建或检索 JPA 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15464311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com