JPA的一个错误(每次执行后转储数据库)?

时间:2012-01-17 20:55:02

标签: java jpa

我有JPA的问题我会详细解释:

我在NetBeans“Java Application”中创建了一个项目,然后右键单击“数据库中的实体类”包我选择了数据库,使用DB的getter,setter和属性创建实体是很好的。 最后:右键单击相同的包“JPA Controller Classes From Entity Classes”并选择之前创建的实体,该文件是使用与DB交互的方法生成的... 到目前为止一切顺利, 但是当我运行项目并在每次操作(创建,查找,...)之后,数据库被转储并且程序继续执行而没有错误,例如,如果我选择在数据库中插入新记录,则删除其他记录并将记录正确插入数据库! ,我不明白为什么,如果你们中的一个人能够解释这个错误,那就太酷了......  这是我的源代码:

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

+ Testt.java(主程序):

 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(从数据库创建(生成)的实体“personne”):

 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(由“personne”实体生成)

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

}

最后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>

提前谢谢^^

1 个答案:

答案 0 :(得分:4)

首次运行后,您需要删除该行

<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
来自persistance.xml文件的

,否则EclipseLink每次都会重新创建表。这就是为什么你发现它是空的。请在wiki中查看。