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 :

Relation bidirectionnelle ManyToMany non persistée


Sujet :

JPA Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 8
    Par défaut Relation bidirectionnelle ManyToMany non persistée
    Bonsoir à tous,
    S'il vous plait, pouvez-vous m'aider ? J'ai deux entités Artist et Cd reliées par une relation ManyToMany. J'ai déclaré un cd3 "possédant" deux Artist a2 et a3 . Lorsque j'ai persisté cd3, je n'ai pas eu d'erreurs. a2, a3 et cd3 ont été enregistrés dans leurs tables, mais il n'y a pas eu d'enregistrement dans la table de jointure? Qu'est-ce que je peux faire ?

    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
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
     
    package entity;
     
    import java.io.Serializable;
    import java.util.List;
    import javax.persistence.*;
     
    @Entity
    public class Artist implements Serializable {
     
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
     
        private String firstName; 
        private String lastName;
        @ManyToMany(cascade = CascadeType.PERSIST)
        @JoinTable(name = "joint_art_cd", joinColumns = @JoinColumn(name = "art_fk"),
                   inverseJoinColumns = @JoinColumn(name = "cd_fk"))
        private List<Cd> cd;
     
        public Artist(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
     
        public Artist() {
        }
     
     
     
        public String getFirstName() {
            return firstName;
        }
     
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
     
        public String getLastName() {
            return lastName;
        }
     
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
     
        public List<Cd> getCd() {
            return cd;
        }
     
        public void setCd(List<Cd> cd) {
            this.cd = cd;
        }
     
     
     
        public Long getId() {
            return id;
        }
     
        public void setId(Long id) {
            this.id = id;
        }
     
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        }
     
        @Override
        public boolean equals(Object object) {
             if (!(object instanceof Artist)) {
                return false;
            }
        Artist other = (Artist) 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 "entity.Artist[ id=" + id + " ]";
    }
     
    }
     
     
     
    package entity;
     
    import java.io.Serializable;
    import java.util.List;
    import javax.persistence.*;
     
    @Entity
    public class Cd implements Serializable {
     
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
     
        private String title;   
        private Float price; 
        private String description; 
     
        @ManyToMany(mappedBy = "cd", cascade = CascadeType.ALL)
        private List<Artist> artists;
     
        public Cd(String title, Float price, String description) {
            this.title = title;
            this.price = price;
            this.description = description;
        }
     
     
        public Cd() {
        }
     
     
     
        public String getTitle() {
            return title;
        }
     
        public void setTitle(String title) {
            this.title = title;
        }
     
        public Float getPrice() {
            return price;
        }
     
        public void setPrice(Float price) {
            this.price = price;
        }
     
        public String getDescription() {
            return description;
        }
     
        public void setDescription(String description) {
            this.description = description;
        }
     
        public List<Artist> getArtists() {
            return artists;
        }
     
        public void setArtists(List<Artist> artists) {
            this.artists = artists;
        }
     
     
     
        public Long getId() {
            return id;
        }
     
        public void setId(Long id) {
            this.id = id;
        }
     
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        }
     
        @Override
        public boolean equals(Object object) {
     
            if (!(object instanceof Cd)) {
                return false;
            }
            Cd other = (Cd) 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 "entity.Cd[ id=" + id + " ]";
        }
     
    }
     
     
     
    package entity;
     
    import entity.Book;
    import java.util.*;
    import javax.persistence.*;
    public class Demo {
     
        public static void main(String[] args) {
            Artist a1 = new Artist("Abdelmalik", "Berrada");
            Artist a2 = new Artist("Yassine", "Daoudi");
            Artist a3 = new Artist("Jamel", "Debbouze");
            Cd cd1 = new Cd("Burnout City", 22.2F, "cd Rock");
            Cd cd2 = new Cd("Gun n Roses", 32.2F, "cd Hard Rock");
            Cd cd3 = new Cd("Nirvana", 62.2F, "cd Metal");
            ArrayList <Cd> lCd1 = new ArrayList<Cd>();
            ArrayList <Artist> lArt1 = new ArrayList<Artist>();
            lCd1.add(cd1);
            lCd1.add(cd2);
            lArt1.add(a2);
            lArt1.add(a3);
            a1.setCd(lCd1);
            cd3.setArtists(lArt1);
            //persist(a1);
            persist(cd3);
        }
     
        private static void persist(Object object) {
            EntityManagerFactory emf =     javax.persistence.Persistence.createEntityManagerFactory("simple-jpaPU");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            try{
                em.persist(object);
                em.getTransaction().commit();
            }
            catch(Exception e){
                e.printStackTrace();
                em.getTransaction().rollback();
            }
            finally{
                em.close();
            }
        }
     
    }

  2. #2
    Expert éminent
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 482
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 46
    Localisation : Belgique

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

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 482
    Par défaut
    Tu n'a jamais définis dans ton code les cds de a2 et a3. Hors d'après ton mapping, c'est bien Artist qui gère la relation.

  3. #3
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 8
    Par défaut Relation bidirectionnelle ManyToMany non persistée
    Lorsque j'attribue cd3 à a2 et a3, et que j'essaye de les persister, j'ai cette erreur :
    "[EclipseLink-4002] : la valeur d'une clé dupliquée rompt la contrainte unique « artist_pkey »
    Détail*: La clé « (id)=(651) » existe déjà.
    Call: INSERT INTO ARTIST (ID, FIRSTNAME, LASTNAME) VALUES (?, ?, ?)
    bind => [3 parameters bound]"

    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
     
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package entity;
     
    /**
     *
     * @author berra
     */
    import entity.Book;
    import java.util.*;
    import javax.persistence.*;
    public class Demo {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            Artist a1 = new Artist("Abdelmalik", "Berrada");
            Artist a2 = new Artist("Yassine", "Daoudi");
            Artist a3 = new Artist("Jamel", "Debbouze");
            Cd cd1 = new Cd("Burnout City", 22.2F, "cd Rock");
            Cd cd2 = new Cd("Gun n Roses", 32.2F, "cd Hard Rock");
            Cd cd3 = new Cd("Nirvana", 62.2F, "cd Metal");
            ArrayList <Cd> lCd1 = new ArrayList<Cd>();
            ArrayList <Artist> lArt1 = new ArrayList<Artist>();
            lCd1.add(cd3);
            lArt1.add(a2);
            lArt1.add(a3);
            a2.setCd(lCd1);
            a3.setCd(lCd1);
            cd3.setArtists(lArt1);
            persist(a2);
            persist(a3);
            persist(cd3);
        }
     
        private static void persist(Object object) {
            EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("simple-jpaPU");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            try{
                em.persist(object);
                em.getTransaction().commit();
            }
            catch(Exception e){
                e.printStackTrace();
                em.getTransaction().rollback();
            }
            finally{
                em.close();
            }
        }
     
    }

  4. #4
    Membre habitué
    Homme Profil pro
    Étudiant
    Inscrit en
    Avril 2014
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 33
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2014
    Messages : 8
    Par défaut Relation bidirectionnelle ManyToMany non persistée
    Merci beaucoup. Finalement, je n'ai persisté que a2, de Artist qui gère la relation. Et les autres objets (a3 et cd3) ont été persistés en cascade : ).

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

Discussions similaires

  1. Réponses: 20
    Dernier message: 26/09/2016, 08h39
  2. Relation ManyToMany et persist pour une modification
    Par gaerebut dans le forum Doctrine2
    Réponses: 2
    Dernier message: 09/08/2012, 09h40
  3. [2.x] ManyToMany, ne persister qu'un coté de la relation
    Par j.boe dans le forum Symfony
    Réponses: 1
    Dernier message: 09/06/2012, 15h01
  4. Relation bidirectionnelle non fonctionnelle
    Par dubitoph dans le forum Doctrine2
    Réponses: 3
    Dernier message: 29/12/2011, 15h39
  5. Réponses: 0
    Dernier message: 31/08/2011, 12h27

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