[java] petite problème avec JPA helps please

Résolu/Fermé
chabacha109 Messages postés 268 Date d'inscription samedi 11 décembre 2010 Statut Membre Dernière intervention 14 mai 2012 - Modifié par chabacha109 le 17/01/2012 à 09:56
choubaka Messages postés 39375 Date d'inscription jeudi 4 avril 2002 Statut Modérateur Dernière intervention 14 avril 2024 - 14 avril 2016 à 10:05
Bonjour,
j'ai un problème avec JPA j'explique :
j'ai crée un projet sous netbeans "Java Application" , ensuite clic droite sur le package "class entité prevenant de la base de donnée" ,j'ai choisi la B.D, c'est bon l'entité est crée avec les getter et setter et les attributs le la B.D
enfin clic droite sur le méme package "JPA Controller From Entity classes" et j'ai choisi l'entité crée tout à l'heure, le fichier est généré avec les methodes d'interaction avec la B.D...
enfin mon probléme c'est avec le constructeur de la class "TableeJpaController":



public TableeJpaController(EntityManagerFactory emf){
...
}



par exemple pour inserer un enregistrement dans la base de donnée je doit instancier une entité dans la methode "Main" , dans mon exemple j'ai "Tablee" (Tablee aussi c'est le nom de la table de B.D avec deux attr id et nom) ensuite invoquer la methode "create(Tablee tablee)" de la classe "TableeJpaController" pour l'inserer :

Tablee t = new Tablee(1,"marwen");
//la suite ??


TableeJpaController
ensuite je suis bloqué a ce stade car je ne connait pas comment instancier la classe "TableeJpaController"
plutot comment instancier "EntityManagerFactory"... voilà
Merci d'avance de votre aide j'attend vivement des réponses :))




To Be Or Not To Be , Marwen
A voir également:

4 réponses

choubaka Messages postés 39375 Date d'inscription jeudi 4 avril 2002 Statut Modérateur Dernière intervention 14 avril 2024 2 100
17 janv. 2012 à 11:40
0
chabacha109 Messages postés 268 Date d'inscription samedi 11 décembre 2010 Statut Membre Dernière intervention 14 mai 2012 9
Modifié par chabacha109 le 17/01/2012 à 19:08
MERCI ça marche !
j'ai un autre problème que je ne comprend pas :
lorsque j'exécute le code il affiche un message "succeed! l'objet est inséré" et l'objet est inséré dans la B.D MAIS il écrase tous les anciens enregistrement et puis il insère,j'ai changé la methode en "tjc.getPersonneCount()" pour que je vérifie le nbr d'enreg mais il me retourne 0, bref chaque fois que j'exécute le programme il vide la table , voilà mon projet:

TesTT.java (le programme principale) :
package testt;   

import javax.persistence.EntityManagerFactory;   
import javax.persistence.Persistence;   
import testt.exceptions.PreexistingEntityException;   

/**   
 *   
 * @author marwen   
 */   
public class Testt {   

    /**   
     * @param args the command line arguments   
     */   
    public static void main(String[] args) throws PreexistingEntityException, Exception {   
           
           
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("testtPU");   
        Personne p=new Personne(2);   
        p.setNom("marwen");   
        PersonneJpaController tjc=new PersonneJpaController(emf);   
          
            tjc.create(p);   
              
            System.out.println("succeed! l'objet est inséré");   
    }   
}   



Personne.java (c'est l'entité personne provenant de la base de donnée):
/*   
 * To change this template, choose Tools | Templates   
 * and open the template in the editor.   
 */   
package testt;   

import java.io.Serializable;   
import javax.persistence.*;   
import javax.xml.bind.annotation.XmlRootElement;   

/**   
 *   
 * @author marwen   
 */   
@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(généré a partir de l'entité Personne)
/*   
 * To change this template, choose Tools | Templates   
 * and open the template in the editor.   
 */   
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;   

/**   
 *   
 * @author marwen   
 */   
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();   
        }   
    }   
       
}




enfin persistance.xml:
<?xml version="1.0" encoding="UTF-8"?>   
<persistence version="2.0" xmlns="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/index.html" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/persistence/index.html http://www.oracle.com/webfolder/technetwork/jsc/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>


Remarque: le Personne.java et PersonneJpaController.java est généré par netbeans a partir la base de donnée j'ai écrit seulement la class Testt.java.

j'ai crée 5 projets et sans résultat... j'ai passé toute la journée devant cette erreur :/
Merci encore pour votre aide ^_^







To Be Or Not To Be , Marwen
0
LousD74 Messages postés 1 Date d'inscription mercredi 13 avril 2016 Statut Membre Dernière intervention 13 avril 2016
13 avril 2016 à 17:07
Salut,
Dans persistance.xml :
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
Change la valeur en create uniquement... Car sinon tu dropes ta table à chaque fois...
0
choubaka Messages postés 39375 Date d'inscription jeudi 4 avril 2002 Statut Modérateur Dernière intervention 14 avril 2024 2 100
14 avril 2016 à 10:05
bonjour
depuis 2012,ça devrait être réglé.
0