IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

avec Java Discussion :

Erreur "NullPointerException"


Sujet :

avec Java

  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Septembre 2011
    Messages
    4
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2011
    Messages : 4
    Points : 2
    Points
    2
    Par défaut Erreur "NullPointerException"
    Bonjour,

    Je suis en train de développer un exercice en JEE, donc j'ai créé une base de données avec les tables Etudiant, Devoir et Note.

    J'ai créé une méthode pour récupérer une liste d'étudiants mais quand je crée un étudiant, j'obtiens l'erreur suivante :
    An error occurred attempting to roll back the transaction
    java.lang.NullPointerException
    Voici mon code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    package fr.note;
     
    import fr.note.entites.Etudiant;
    import fr.note.service.ClientEjbNoteRemote;
    import java.util.List;
    import javax.ejb.EJB;
     
     
    public class client_lourd {
       @EJB
       private static ClientEjbNoteRemote ejbNote;
       private static final int NUM =7;
       private static final String NOM="sam";
       private static final String PRENOM = "sam";
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
           /*List<Etudiant> liste = ejbNote.ListEtudiant();
            for(Etudiant e : liste){
            System.out.println(e.getPrenom() + "\t" + e.getNom());
        }*/
            Etudiant etudiant = new Etudiant(NUM);
            ejbNote.InsererEtudiant(etudiant);
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    package fr.note.service;
     
    import fr.note.entites.Etudiant;
    import java.util.List;
    import javax.ejb.Remote;
     
    @Remote
    public interface ClientEjbNoteRemote {
        public List<Etudiant> ListEtudiant();
     
        public void InsererEtudiant(Etudiant etudiant);
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    package fr.note.persisatnce;
     
    import fr.note.entites.Etudiant;
    import fr.note.persisatnce.exceptions.NonexistentEntityException;
    import fr.note.persisatnce.exceptions.RollbackFailureException;
    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 javax.transaction.UserTransaction;
     
     
    public class EtudiantJpaController implements Serializable {
     
        public EtudiantJpaController(UserTransaction utx, EntityManagerFactory emf) {
            this.utx = utx;
            this.emf = emf;
        }
        private UserTransaction utx = null;
        private EntityManagerFactory emf = null;
     
        public EntityManager getEntityManager() {
            return emf.createEntityManager();
        }
     
        public void create(Etudiant etudiant) throws RollbackFailureException, Exception {
            EntityManager em = null;
            try {
                utx.begin();
                em = getEntityManager();
                em.persist(etudiant);
                utx.commit();
            } catch (Exception ex) {
                try {
                    utx.rollback();
                } catch (Exception re) {
                    throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
                }
                throw ex;
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
     
        public void edit(Etudiant etudiant) throws NonexistentEntityException, RollbackFailureException, Exception {
            EntityManager em = null;
            try {
                utx.begin();
                em = getEntityManager();
                etudiant = em.merge(etudiant);
                utx.commit();
            } catch (Exception ex) {
                try {
                    utx.rollback();
                } catch (Exception re) {
                    throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
                }
                String msg = ex.getLocalizedMessage();
                if (msg == null || msg.length() == 0) {
                    Integer id = etudiant.getNumEtudiant();
                    if (findEtudiant(id) == null) {
                        throw new NonexistentEntityException("The etudiant with id " + id + " no longer exists.");
                    }
                }
                throw ex;
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
     
        public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
            EntityManager em = null;
            try {
                utx.begin();
                em = getEntityManager();
                Etudiant etudiant;
                try {
                    etudiant = em.getReference(Etudiant.class, id);
                    etudiant.getNumEtudiant();
                } catch (EntityNotFoundException enfe) {
                    throw new NonexistentEntityException("The etudiant with id " + id + " no longer exists.", enfe);
                }
                em.remove(etudiant);
                utx.commit();
            } catch (Exception ex) {
                try {
                    utx.rollback();
                } catch (Exception re) {
                    throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
                }
                throw ex;
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
     
        public List<Etudiant> findEtudiantEntities() {
            return findEtudiantEntities(true, -1, -1);
        }
     
        public List<Etudiant> findEtudiantEntities(int maxResults, int firstResult) {
            return findEtudiantEntities(false, maxResults, firstResult);
        }
     
        private List<Etudiant> findEtudiantEntities(boolean all, int maxResults, int firstResult) {
            EntityManager em = getEntityManager();
            try {
                CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
                cq.select(cq.from(Etudiant.class));
                Query q = em.createQuery(cq);
                if (!all) {
                    q.setMaxResults(maxResults);
                    q.setFirstResult(firstResult);
                }
                return q.getResultList();
            } finally {
                em.close();
            }
        }
     
        public Etudiant findEtudiant(Integer id) {
            EntityManager em = getEntityManager();
            try {
                return em.find(Etudiant.class, id);
            } finally {
                em.close();
            }
        }
     
        public int getEtudiantCount() {
            EntityManager em = getEntityManager();
            try {
                CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
                Root<Etudiant> rt = cq.from(Etudiant.class);
                cq.select(em.getCriteriaBuilder().count(rt));
                Query q = em.createQuery(cq);
                return ((Long) q.getSingleResult()).intValue();
            } finally {
                em.close();
            }
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    package fr.note.service;
     
    import fr.note.entites.Etudiant;
    import fr.note.persisatnce.EtudiantJpaController;
    import fr.note.persisatnce.exceptions.RollbackFailureException;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
     
     
    @Stateless
    public class ClientEjbNote implements ClientEjbNoteRemote, ClientEjbNoteLocal {
     
        @Override
        public List<Etudiant> ListEtudiant(){
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("NFE114-Note-JEE-ejbPU");
            EtudiantJpaController daoEtudiant = new EtudiantJpaController(null, emf);
            List<Etudiant> liste = daoEtudiant.findEtudiantEntities();
            return liste;
        }
        @Override
        public void InsererEtudiant(Etudiant etudiant){
            try {
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("NFE114-Note-JEE-ejbPU");
                EtudiantJpaController daoEtudiant = new EtudiantJpaController(null,emf);
                daoEtudiant.create(etudiant);
            } catch (RollbackFailureException ex) {
                Logger.getLogger(ClientEjbNote.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(ClientEjbNote.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    package fr.note.service;
     
    import fr.note.entites.Etudiant;
    import fr.note.persisatnce.exceptions.RollbackFailureException;
    import java.util.List;
    import javax.ejb.Local;
     
    @Local
    public interface ClientEjbNoteLocal {
     
        public List<Etudiant> ListEtudiant();
        public void InsererEtudiant(Etudiant etudiant);
    }
    Quelqu'un saurait-il m'indiquer d'où peut venir le problème ?

    Merci d'avance pour votre aide.

  2. #2
    Membre éclairé
    Avatar de maxusn
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2012
    Messages
    174
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2012
    Messages : 174
    Points : 661
    Points
    661
    Par défaut
    Bonjour, j'ai peut etre loupé quelque chose mais tu fais

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    EtudiantJpaController daoEtudiant = new EtudiantJpaController(null,emf);
    donc ton utx vaut null, et jamais tu ne lui assignes une autre valeur (ou je ne l'ais pas vu et je m'en excuse)

    ensuite tu fais
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    daoEtudiant.create(etudiant);
    dans cette fonction tu essayes de faire un
    mais utx étant null tu passes dans ton exception :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    catch (Exception ex) {
                try {
                    utx.rollback();
                } catch (Exception re) {
                    throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
                }
    tu essaye donc de faire un rollaback sur un objet null et donc une nouvelle fois tu passes dans une exception, celle que tu as définis :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    hrow new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);

  3. #3
    Candidat au Club
    Profil pro
    Inscrit en
    Septembre 2011
    Messages
    4
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2011
    Messages : 4
    Points : 2
    Points
    2
    Par défaut
    Bonjour,
    Merci pour votre réponse
    utx est null car au départ aucune transaction est court, et utx.begin() commencera une transaction il va essayer d'ajouter le tuple 'etudiant' et si tout se passe bien il fait un commit() sino il génère une exception et le rolback pour revenir à l'état initial avant le begin()
    peut être je e trompe alors excusez moi
    en tout je suis toujours au même point
    si utx(UserTransaction) doit prendre une valeur non nulle qu'elle valeurs dois-je lui attribuer
    ps : pour récupérer la liste des étudiant j'ai aucun problème et pourtant j'ai mis la valeur null pour utx
    merci beaucoup et bonne journée

  4. #4
    Membre du Club
    Inscrit en
    Février 2010
    Messages
    43
    Détails du profil
    Informations forums :
    Inscription : Février 2010
    Messages : 43
    Points : 64
    Points
    64
    Par défaut
    Hello,

    Il me semble qu'il faut faire comme sa :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
     
    public void create(Etudiant etudiant) throws RollbackFailureException, Exception {
            EntityManager em = null;
            try {
                em = getEntityManager();
                utx = em.getTransaction();
                utx.begin();
                em.persist(etudiant);
                utx.commit();
            } catch (Exception ex) {
                try {
                    utx.rollback();
                } catch (Exception re) {
                    throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
                }
                throw ex;
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    EtudiantJpaController daoEtudiant = new EtudiantJpaController(null,emf);

    tu essaies de faire null.begin()

    Cordialement,
    Dali

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo