Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA EntityManager deletes all records in database

I have one Servlet that does insertion into my database. This is working fine. A second Servlet displays what the first one has inserted, however whenever I run the displaying Servlet, all records in all my tables are being deleted! My JPA implementation is EclipseLink and the db is MySQL.

Is it possible that the way I retrieve a EntityManagerFactory is triggering a recreation of the db schema?

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);

My 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>

like image 938
Leonard Ehrenfried Avatar asked Jan 23 '23 09:01

Leonard Ehrenfried


1 Answers

It's exactly as you suspect. According to the [EclipseLink docs](http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)) The line

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

makes the EclipseLink delete all the tables on startup.

Consider using create-tables instead.

like image 98
Grzegorz Oledzki Avatar answered Jan 25 '23 22:01

Grzegorz Oledzki