Marwen Trabelsi
Marwen Trabelsi

Reputation: 4257

A bug with JPA (Dump the database after each execution)?

I have a problem with JPA I will explain in detail:

I created a project in NetBeans "Java Application", then right click on the package "Entity Classes From Data Base" I chose the DB, it's good the entity is created with getters, setters and attributes of DB. finally: right click on the same package "JPA Controller Classes From Entity Classes " and I chose the entity created earlier, the file is generated with the methods of interaction with DB... All is going well so far, But when I run the project and after each operation (create, find, ..) the database is dumped and the program continues the execution without errors, for example if I chose to insert a new record in the DB , the other records are deleted and the record is inserted into the DB correctly! , I do not understand why, if one of you can explain this error it will be too cool... here is my source code:

 +Here I have a database its called "personne" containing only a one table also called   "personne"(id=int,nom=varchar(30)).

+Testt.java (the main program) :

 package testt;

 import javax.persistence.EntityManagerFactory;

 import javax.persistence.Persistence;

 import testt.exceptions.PreexistingEntityException;


 public class Testt {
 public static void main(String[] args) throws PreexistingEntityException, Exception {


 EntityManagerFactory emf = Persistence.createEntityManagerFactory("testtPU");
 Personne p=new Personne(2);
 p.setNom("ME ME");
 PersonneJpaController tjc=new PersonneJpaController(emf);

 tjc.create(p);

 System.out.println("succeed! ");
 }
 }

Personne.java (the entity "personne" its created(generated) from the database):

 package testt;

 import java.io.Serializable;
 import javax.persistence.*;
 import javax.xml.bind.annotation.XmlRootElement;
 @Entity
 @Table(name = "PERSONNE", catalog = "", schema = "ROOT")
 @XmlRootElement
 @NamedQueries({
 @NamedQuery(name = "Personne.findAll", query = "SELECT p FROM Personne p"),
 @NamedQuery(name = "Personne.findById", query = "SELECT p FROM Personne p WHERE p.id =           :id"),
 @NamedQuery(name = "Personne.findByNom", query = "SELECT p FROM Personne p WHERE p.nom = :nom")})
public class Personne implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "ID", nullable = false)
private Integer id;
@Column(name = "NOM", length = 30)
private String nom;

public Personne() {
}

public Personne(Integer id) {
    this.id = id;
}

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getNom() {
    return nom;
}

public void setNom(String nom) {
    this.nom = nom;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (id != null ? id.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof Personne)) {
        return false;
    }
    Personne other = (Personne) object;
    if ((this.id == null && other.id != null) || (this.id != null &&     !this.id.equals(other.id))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "testt.Personne[ id=" + id + " ]";
}

}

PersonneJpaController.java(generated from the "personne" entity)

 package testt;

 import java.io.Serializable;
 import java.util.List;
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.Query;
 import javax.persistence.EntityNotFoundException;
 import javax.persistence.criteria.CriteriaQuery;
 import javax.persistence.criteria.Root;
 import testt.exceptions.NonexistentEntityException;
 import testt.exceptions.PreexistingEntityException;


 public class PersonneJpaController implements Serializable {

 public PersonneJpaController(EntityManagerFactory emf) {
     this.emf = emf;
} 
private EntityManagerFactory emf = null;

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}

public void create(Personne personne) throws PreexistingEntityException, Exception {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        em.persist(personne);
        em.getTransaction().commit();
    } catch (Exception ex) {
        if (findPersonne(personne.getId()) != null) {
            throw new PreexistingEntityException("Personne " + personne + " already exists.", ex);
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void edit(Personne personne) throws NonexistentEntityException, Exception {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        personne = em.merge(personne);
        em.getTransaction().commit();
    } catch (Exception ex) {
        String msg = ex.getLocalizedMessage();
        if (msg == null || msg.length() == 0) {
            Integer id = personne.getId();
            if (findPersonne(id) == null) {
                throw new NonexistentEntityException("The personne with id " + id + " no longer exists.");
            }
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void destroy(Integer id) throws NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Personne personne;
        try {
            personne = em.getReference(Personne.class, id);
            personne.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The personne with id " + id + " no longer exists.", enfe);
        }
        em.remove(personne);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public List<Personne> findPersonneEntities() {
    return findPersonneEntities(true, -1, -1);
}

public List<Personne> findPersonneEntities(int maxResults, int firstResult) {
    return findPersonneEntities(false, maxResults, firstResult);
}

private List<Personne> findPersonneEntities(boolean all, int maxResults, int firstResult) {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Personne.class));
        Query q = em.createQuery(cq);
        if (!all) {
            q.setMaxResults(maxResults);
            q.setFirstResult(firstResult);
        }
        return q.getResultList();
    } finally {
        em.close();
    }
}

public Personne findPersonne(Integer id) {
    EntityManager em = getEntityManager();
    try {
        return em.find(Personne.class, id);
    } finally {
        em.close();
    }
}

public int getPersonneCount() {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<Personne> rt = cq.from(Personne.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    } finally {
        em.close();
    }
 }

}

finally persistance.xml:

 <?xml version="1.0" encoding="UTF-8"?>
 <persistence version="2.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_2_0.xsd">
 <persistence-unit name="testtPU" transaction-type="RESOURCE_LOCAL">
 <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
 <class>testt.Personne</class>
 <properties>
 <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/personne"/>
 <property name="javax.persistence.jdbc.password" value="1234"/>
 <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
 <property name="javax.persistence.jdbc.user" value="root"/>
 <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
 </properties>
 </persistence-unit>
 </persistence>

thank you in advance ^^

Upvotes: 2

Views: 387

Answers (1)

perissf
perissf

Reputation: 16273

After the first run, you need to remove the line

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

from the persistance.xml file, otherwise EclipseLink will re-create the table each time. That's why you find it empty. Check it out in the wiki.

Upvotes: 4

Related Questions