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

JPA Java Discussion :

Comment ajouter un element OneToMany fils using JPA


Sujet :

JPA Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Inscrit en
    Février 2010
    Messages
    20
    Détails du profil
    Informations forums :
    Inscription : Février 2010
    Messages : 20
    Par défaut Comment ajouter un element OneToMany fils using JPA
    Salut,

    J'arrive pas à ajouter un objet fils:

    j'ai deux entité: Parent et Child.
    J'aimerai ajouter un nouveau Child pour un Parent donner.

    voila ce que j'ai dejà essayer:

    Entité Parent
    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
    public class Parent {
        @Id 
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int parentId;
        private String parentName;
     
        @OneToMany(mappedBy="parent") 
        private List<Child> children = new ArrayList<Child>();
        ... 
     
            public void addChildToParent(Child c) {
            c.setParent(this);
            children.add(c);
        }
      }
    Entité Child
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public class Child {
        @Id 
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int childId;
        private String childName;
     
        @ManyToOne 
        private Parent parent;
        ...
    Servlet
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        String childName = request.getParameter("childName");
        int parentId = Integer.parseInt(request.getParameter("parentId"));
     
        Child newChild = new Child();
        Parent ParentOfChild = new Parent();
     
        newChild.setChildName(childName);
        ParentOfChild.addChildToParent(newChild);
     
        ParentOfChild = parentDao.getParent(parentId);
        parentDao.editParent(ParentOfChild);
     
    ...

  2. #2
    Membre Expert
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2007
    Messages
    2 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 2 938
    Par défaut
    Bonjour,
    C'est pas compliqué :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
     
    //On commence par attacher le Parent au contexte de Persistence Hibernate==>Très important
    Parent parentOfChild = parentDao.getParent(parentId);
    Child newChild = new Child();
    newChild.setParent(parentOfChild);
    ...
    En conclusion c'est plutot au fils qu'on indique qui est son parent, l'inverse est souvent compliquée à réaliser.Une dernière chose les instances en Java commencent par une lettre minuscule.

  3. #3
    Membre expérimenté
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Septembre 2011
    Messages
    196
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2011
    Messages : 196
    Par défaut
    sur ton champ children, il faut rajouter l'attribut cascade=CascadeType.ALL, de cette façon il insérera automatiquement les enfants qui seront ajoutés au parent.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    @OneToMany(mappedBy="parent",cascade = CascadeType.ALL) 
    private List<Child> children = new ArrayList<Child>();

  4. #4
    Membre Expert
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2007
    Messages
    2 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 2 938
    Par défaut
    Citation Envoyé par oliv37 Voir le message
    sur ton champ children, il faut rajouter l'attribut cascade=CascadeType.ALL, de cette façon il insérera automatiquement les enfants qui seront ajoutés au parent.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    @OneToMany(mappedBy="parent",cascade = CascadeType.ALL) 
    private List<Child> children = new ArrayList<Child>();
    Euh ... pas forcément le ALL, qui lui inclut beaucoup (MERGE,REFRESH,REMOVE, PERSIST)etc...
    Pour son besoin ceci pourrait suffir aussi :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    @OneToMany(mappedBy="parent",cascade = CascadeType.PERSIST)
    Personnellement je n'utilise pas souvent cette annotation car je préfère avoir la main , mais c'est un choix perso.

  5. #5
    Membre averti
    Inscrit en
    Février 2010
    Messages
    20
    Détails du profil
    Informations forums :
    Inscription : Février 2010
    Messages : 20
    Par défaut
    Citation Envoyé par oliv37 Voir le message
    sur ton champ children, il faut rajouter l'attribut cascade=CascadeType.ALL, de cette façon il insérera automatiquement les enfants qui seront ajoutés au parent.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    @OneToMany(mappedBy="parent",cascade = CascadeType.ALL) 
    private List<Child> children = new ArrayList<Child>();
    J'ai ajouter les deux cascade. Persist et All mais ya toujours cette erreur

  6. #6
    Membre Expert
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2007
    Messages
    2 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 2 938
    Par défaut
    Y'a un NullPointer :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    at com.controller.AddChild.doPost(AddChild.java:84)
    Essaie de mettre un point d'arrêt ou affiche des println pour voir où tu as l'objet null, nous n'avons pas accès à AddChild.

  7. #7
    Membre averti
    Inscrit en
    Février 2010
    Messages
    20
    Détails du profil
    Informations forums :
    Inscription : Février 2010
    Messages : 20
    Par défaut
    Citation Envoyé par DevServlet Voir le message
    Y'a un NullPointer :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    at com.controller.AddChild.doPost(AddChild.java:84)
    Essaie de mettre un point d'arrêt ou affiche des println pour voir où tu as l'objet null, nous n'avons pas accès à AddChild.
    c'est quoi un point d’arrête?

    J'ai fait un printf au niveau du ligne signe du servlet pour voir si les element saisi sont recuperer de la page JSP, et il le sont...

    Je viens d'uploader le projet sur DropBox

    Je m'excuse pour ces questions... Je suis nouveau en JEE World :/

  8. #8
    Membre averti
    Inscrit en
    Février 2010
    Messages
    20
    Détails du profil
    Informations forums :
    Inscription : Février 2010
    Messages : 20
    Par défaut
    Citation Envoyé par DevServlet Voir le message
    Bonjour,
    C'est pas compliqué :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
     
    //On commence par attacher le Parent au contexte de Persistence Hibernate==>Très important
    Parent parentOfChild = parentDao.getParent(parentId);
    Child newChild = new Child();
    newChild.setParent(parentOfChild);
    ...
    En conclusion c'est plutot au fils qu'on indique qui est son parent, l'inverse est souvent compliquée à réaliser.Une dernière chose les instances en Java commencent par une lettre minuscule.
    Ok merci beaucoup,
    Donc d'apres ce que j'ai compris, voila le code après modification.
    Mais la j'ai une erreur:

    Servlet:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     String childName = request.getParameter("childName");
            int parentId = Integer.parseInt(request.getParameter("parentId"));
     
            Parent ParentOfChild = parentDao.getParent(parentId);
     
            Child newChild = new Child();
     
            newChild.setParent(ParentOfChild);        
            newChild.setChildName(childName); 
     
            childDao.addChild(newChild);
     
     
            request.getRequestDispatcher("addChild.jsp").forward(request, response);
    Voila le log du serveur:
    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
    INFO: file:/C:/Users/WORK/Documents/NetBeansProjects/CRUDWebBasic/build/web/WEB-INF/classes/_CRUDWebBasicPU logout successful
    INFO: Portable JNDI names for EJB ChildDao : [java:global/CRUDWebBasic/ChildDao, java:global/CRUDWebBasic/ChildDao!com.dao.ChildDaoLocal]
    INFO: Portable JNDI names for EJB ParentDao : [java:global/CRUDWebBasic/ParentDao!com.dao.ParentDaoLocal, java:global/CRUDWebBasic/ParentDao]
    INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    INFO: EclipseLink, version: Eclipse Persistence Services - 2.0.1.v20100213-r6600
    INFO: file:/C:/Users/WORK/Documents/NetBeansProjects/CRUDWebBasic/build/web/WEB-INF/classes/_CRUDWebBasicPU login successful
    ATTENTION: Got SQLException executing statement "CREATE TABLE CHILD (CHILDID INTEGER NOT NULL, CHILDNAME VARCHAR(255), PARENT_PARENTID INTEGER, PRIMARY KEY (CHILDID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'child' already exists
    ATTENTION: Got SQLException executing statement "CREATE TABLE PARENT (PARENTID INTEGER NOT NULL, PARENTNAME VARCHAR(255), PRIMARY KEY (PARENTID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'parent' already exists
    ATTENTION: Got SQLException executing statement "ALTER TABLE CHILD ADD CONSTRAINT FK_CHILD_PARENT_PARENTID FOREIGN KEY (PARENT_PARENTID) REFERENCES PARENT (PARENTID)": java.sql.SQLException: Can't create table 'crudwebbasic.#sql-a48_58' (errno: 121)
    ATTENTION: Got SQLException executing statement "CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(38), PRIMARY KEY (SEQ_NAME))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'sequence' already exists
    ATTENTION: Got SQLException executing statement "INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)": com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'SEQ_GEN' for key 'PRIMARY'
    INFO: Loading application CRUDWebBasic at /CRUDWebBasic
    INFO: CRUDWebBasic was successfully deployed in 968 milliseconds.
    ATTENTION: StandardWrapperValve[AddChild]: PWC1406: Servlet.service() for servlet AddChild threw exception
    java.lang.NullPointerException
    	at com.controller.AddChild.processRequest(AddChild.java:49)
    	at com.controller.AddChild.doPost(AddChild.java:84)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
    	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
    	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
    	at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
    	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
    	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
    	at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
    	at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
    	at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
    	at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
    	at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
    	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
    	at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
    	at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
    	at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
    	at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
    	at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
    	at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
    	at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
    	at java.lang.Thread.run(Thread.java:619)

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. C# aspx vs2005 comment ajouter un element a ma listbox
    Par arioule dans le forum ASP.NET
    Réponses: 2
    Dernier message: 07/12/2006, 13h29
  2. comment ajouter un element à une JList
    Par belassel_z dans le forum Composants
    Réponses: 1
    Dernier message: 20/05/2006, 12h13
  3. Réponses: 5
    Dernier message: 08/05/2006, 22h32
  4. Réponses: 2
    Dernier message: 07/12/2005, 03h21
  5. [netbean 5 dev] comment ajouter Mes elements en visuel
    Par alain57 dans le forum NetBeans
    Réponses: 1
    Dernier message: 14/10/2005, 05h38

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