JPA EntityManager删除数据库中的所有记录

时间:2009-08-04 13:26:37

标签: java jpa eclipselink

我有一个插入我的数据库的Servlet。这工作正常。第二个Servlet显示第一个插入的内容,但每当我运行显示的Servlet时,我所有表中的所有记录都将被删除!我的JPA实现是EclipseLink,db是MySQL。

我检索EntityManagerFactory的方式是否可能触发重新创建数据库模式?

EntityManagerFactory factory;
factory = Persistence.createEntityManagerFactory("gate");
EntityManager em = factory.createEntityManager();

List list;
try{
   Query query = em.createQuery("SELECT i from PersistentItem i");
   list= query.getResultList();

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

}finally{
        em.close();
    }

Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("title", "List of all items");
myModel.put("itemList", list);

return new ModelAndView("list", "model", myModel);

我的persistence.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="gate" transaction-type="RESOURCE_LOCAL">
    <description>Eclipselink</description>
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

    <class>info.lenni.gate.persistence.PersistentItem</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="eclipselink.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="eclipselink.jdbc.url" value="jdbc:mysql://localhost:3306/gate" />

        <property name="eclipselink.jdbc.user" value="root" />
        <property name="eclipselink.jdbc.password" value="" />

        <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="OFF"/>
    </properties>
</persistence-unit>

1 个答案:

答案 0 :(得分:9)

正如你所怀疑的那样。根据[EclipseLink docs](http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG))

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

使EclipseLink在启动时删除所有表。

请考虑使用create-tables