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

Développement Web en Java Discussion :

Etat détacher d'une entity


Sujet :

Développement Web en Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Inscrit en
    Septembre 2010
    Messages
    121
    Détails du profil
    Informations forums :
    Inscription : Septembre 2010
    Messages : 121
    Par défaut Etat détacher d'une entity
    Bonjour tout le monde, je suis entrain de faire une application en JavaEE avec server glassfish et JSF/facelet.Tout mon programme marche sauf que j'ai un problème sur mon Entity Manager em.remove j'ai une exeption, une belle stack trace :

    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
    Caused by: javax.ejb.EJBException
    	at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5119)
    	at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5017)
    	at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4805)
    	at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2004)
    	at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1955)
    	at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:198)
    	at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84)
    	at $Proxy116.removeTicket(Unknown Source)
    	at managed.bean.TicketController.deleteTicket(TicketController.java:180)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at com.sun.el.parser.AstValue.invoke(AstValue.java:234)
    	at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:297)
    	at com.sun.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:68)
    	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    	... 38 more
    Caused by: java.lang.IllegalArgumentException: Entity must be managed to call remove: suptrac.entity.bean.Ticket[id=602], try merging the detached and try the remove again.
    	at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.performRemove(UnitOfWorkImpl.java:3539)
    Comme on peut le voir a la fin de mon message mon entity est dans un état détacher et ne peut pas être remove.J'ai donc essayer de tricher un petit coup en faisant un em.merge() mais rien n'y fais
    Voila mon Managed Bean
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
        public String deleteTicket() {
     
            ticketSessionBean.removeTicket(ticket);
            return "go-to-new";
        }
    Voila mon SessionBean :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
       public void removeTicket(Ticket ticket) {
            em.merge(ticket);
            em.remove(ticket);
        }
    Voila mon EntityBean :
    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
     
    package suptrac.entity.bean;
     
    import java.io.Serializable;
    import java.util.Date;
    import java.util.List;
    import javax.persistence.CascadeType;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import suptrac.statuses.priorities.TicketPriority;
    import suptrac.statuses.priorities.TicketStatus;
     
    /**
     *
     * @author bush
     */
    @Entity
    @Table(name="TICKETS")
    public class Ticket implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String summary;
        private String description;
        private TicketPriority priority;
        private TicketStatus status;
        @Temporal(javax.persistence.TemporalType.TIMESTAMP)
        private Date creationDate;
        @ManyToOne
        private ProductOwner reporter;
        @ManyToOne
        private Developer developer;
     
        @OneToMany(cascade=CascadeType.ALL, mappedBy = "ticket")
        private List<Comment> comments;
     
        public List<Comment> getComments() {
            return comments;
        }
     
        public void setComments(List<Comment> comments) {
            this.comments = comments;
        }
     
        public Date getCreationDate() {
            return creationDate;
        }
     
        public void setCreationDate(Date creationDate) {
            this.creationDate = creationDate;
        }
     
        public String getDescription() {
            return description;
        }
     
        public void setDescription(String description) {
            this.description = description;
        }
     
        public Developer getDeveloper() {
            return developer;
        }
     
        public void setDeveloper(Developer developer) {
            this.developer = developer;
        }
     
        public TicketPriority getPriority() {
            return priority;
        }
     
        public void setPriority(TicketPriority priority) {
            this.priority = priority;
        }
     
        public ProductOwner getReporter() {
            return reporter;
        }
     
        public void setReporter(ProductOwner reporter) {
            this.reporter = reporter;
        }
     
        public TicketStatus getStatus() {
            return status;
        }
     
        public void setStatus(TicketStatus status) {
            this.status = status;
        }
     
        public String getSummary() {
            return summary;
        }
     
        public void setSummary(String summary) {
            this.summary = summary;
        }
     
     
        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) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Ticket)) {
                return false;
            }
            Ticket other = (Ticket) 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 "suptrac.entity.bean.Ticket[id=" + id + "]";
        }

  2. #2
    Modérateur
    Avatar de OButterlin
    Homme Profil pro
    Inscrit en
    Novembre 2006
    Messages
    7 313
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Novembre 2006
    Messages : 7 313
    Billets dans le blog
    1
    Par défaut
    Essaye ceci
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    public void removeTicket(Ticket ticket) 
    {
        em.remove(em.merge(ticket));
    }
    Si tu relis la doc sur merge, la méthode renvoie une instance "managé" de l'objet en paramètre tout en laissant celui-ci "non managé".
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  3. #3
    Membre confirmé
    Inscrit en
    Septembre 2010
    Messages
    121
    Détails du profil
    Informations forums :
    Inscription : Septembre 2010
    Messages : 121
    Par défaut
    Merci beaucoup ca marche niquel quand le Ticket est vierge sans aucun Commentaire mais maintenent quand je rajoute des commentaire et que je veux delete le ticket alors bim une autre Stack Trace :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
    	at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:450)
    	at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:837)
    	at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5040)
    	... 53 more
    Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`suptrac`.`comments`, CONSTRAINT `FK_COMMENTS_TICKET_ID` FOREIGN KEY (`TICKET_ID`) REFERENCES `tickets` (`ID`))
    Error Code: 1451
    Call: DELETE FROM TICKETS WHERE (ID = ?)
    	bind => [3]
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`suptrac`.`comments`, CONSTRAINT `FK_COMMENTS_TICKET_ID` FOREIGN KEY (`TICKET_ID`) REFERENCES `tickets` (`ID`))
    Mon Entity Bean Ticket
    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
     
    package suptrac.entity.bean;
     
    import java.io.Serializable;
    import java.util.Date;
    import java.util.List;
    import javax.persistence.CascadeType;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import suptrac.statuses.priorities.TicketPriority;
    import suptrac.statuses.priorities.TicketStatus;
     
    /**
     *
     * @author bush
     */
    @Entity
    @Table(name="TICKETS")
    public class Ticket implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String summary;
        private String description;
        private TicketPriority priority;
        private TicketStatus status;
        @Temporal(javax.persistence.TemporalType.TIMESTAMP)
        private Date creationDate;
        @ManyToOne
        private ProductOwner reporter;
        @ManyToOne
        private Developer developer;
     
        @OneToMany(cascade=CascadeType.ALL, mappedBy = "ticket")
        private List<Comment> comments;
     
        public List<Comment> getComments() {
            return comments;
        }
     
        public void setComments(List<Comment> comments) {
            this.comments = comments;
        }
     
        public Date getCreationDate() {
            return creationDate;
        }
     
        public void setCreationDate(Date creationDate) {
            this.creationDate = creationDate;
        }
     
        public String getDescription() {
            return description;
        }
     
        public void setDescription(String description) {
            this.description = description;
        }
     
        public Developer getDeveloper() {
            return developer;
        }
     
        public void setDeveloper(Developer developer) {
            this.developer = developer;
        }
     
        public TicketPriority getPriority() {
            return priority;
        }
     
        public void setPriority(TicketPriority priority) {
            this.priority = priority;
        }
     
        public ProductOwner getReporter() {
            return reporter;
        }
     
        public void setReporter(ProductOwner reporter) {
            this.reporter = reporter;
        }
     
        public TicketStatus getStatus() {
            return status;
        }
     
        public void setStatus(TicketStatus status) {
            this.status = status;
        }
     
        public String getSummary() {
            return summary;
        }
     
        public void setSummary(String summary) {
            this.summary = summary;
        }
     
     
        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) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Ticket)) {
                return false;
            }
            Ticket other = (Ticket) 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 "suptrac.entity.bean.Ticket[id=" + id + "]";
        }
     
    }
    Mon Entity Bean Comment
    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
     
     
    package suptrac.entity.bean;
     
    import java.io.Serializable;
    import java.util.Date;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
     
    /**
     *
     * @author bush
     */
    @Entity
    @Table(name="COMMENTS")
    public class Comment implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        private String content;
        @Temporal(javax.persistence.TemporalType.TIMESTAMP)
        private Date creationDate;
     
        @ManyToOne
        private User author;
        @ManyToOne
        private Ticket ticket;
     
        public User getAuthor() {
            return author;
        }
     
        public void setAuthor(User author) {
            this.author = author;
        }
     
        public String getContent() {
            return content;
        }
     
        public void setContent(String content) {
            this.content = content;
        }
     
        public Date getCreationDate() {
            return creationDate;
        }
     
        public void setCreationDate(Date creationDate) {
            this.creationDate = creationDate;
        }
     
        public Ticket getTicket() {
            return ticket;
        }
     
        public void setTicket(Ticket ticket) {
            this.ticket = ticket;
        }
     
     
        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) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Comment)) {
                return false;
            }
            Comment other = (Comment) 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 "suptrac.entity.bean.Comment[id=" + id + "]";
        }
     
    }
    Comme vous pouvez le voir un ticket a une liste de comment.
    Donc quand j'essai de delete le ticket seul(sans commentaire) ca marche, pas de problème.
    Par contre quand j'essai de delete un Ticket avec des Comments boum l'erreur.
    Je comprend pas trop j'ai bien dans mon EntityBean Ticket
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
      @OneToMany(cascade=CascadeType.ALL, mappedBy = "ticket")
        private List<Comment> comments;
    Normalement ça devrait effacer les tickets aussi quand je fais un Delete?

    En tout cas Merci beaucoup pour ton aide OButterlin

  4. #4
    Modérateur
    Avatar de OButterlin
    Homme Profil pro
    Inscrit en
    Novembre 2006
    Messages
    7 313
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Novembre 2006
    Messages : 7 313
    Billets dans le blog
    1
    Par défaut
    Comme ton entity Comment a une référence sur Ticket et que tu as paramétré ta relation OneToMany avec un CascadeType.ALL, ça me semble normal.

    Soit tu fais :
    - démarrage transaction
    - charges Ticket et ses Comment
    - boucle sur les Comment pour suppression avec retrait de la liste
    - suppression de Ticket
    - validation transaction
    (plutôt lourd)

    soit tu changes la cascade pour ne garder que PERSIST, MERGE, REFRESH et tu utilises la contrainte d'intégrité référentielle avec un delete=cascade pour supprimer les "fils" de Ticket

    En fonction de l'ORM et de la version du JPA, tu peux également voir la solution de CascadeType.DELETE_ORPHAN.

    (personnellement, je préfère la 2)
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  5. #5
    Membre confirmé
    Inscrit en
    Septembre 2010
    Messages
    121
    Détails du profil
    Informations forums :
    Inscription : Septembre 2010
    Messages : 121
    Par défaut
    Sérieusement Merci beaucoup. Oui moi aussi la 2ème solution me parait mieux

  6. #6
    Invité de passage
    Profil pro
    Inscrit en
    Décembre 2010
    Messages
    1
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2010
    Messages : 1
    Par défaut
    Salut Malatok,

    J'ai jeté un petit coup d'oeil à ton code et si j'ai bien compris d'après tes entity beans, tu développes une application pour la gestion de tickets ?
    Je suis actuellement en alternance dans une entreprise qui souhaiterai développer une application de ce type, mais je t'avouerai que je m'y perds un peu ayant commencé à m'intéresser au J2EE il y a peu ...
    Pourrais-tu m'envoyer ton projet que je regarde un peu comment est structuré un projet de ce type ? Tu m'aiderais beaucoup

    Si tu le veux bien, mon adresse est la suivante: paul.duparcq8 aT gmail.com

    Merci d'avance !

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

Discussions similaires

  1. Etat : Affichage d'une étiquette en vertical
    Par Aegnor dans le forum IHM
    Réponses: 9
    Dernier message: 16/03/2006, 17h29
  2. Etat bloqué par une table
    Par aujero dans le forum Access
    Réponses: 4
    Dernier message: 06/02/2006, 17h53
  3. [Etat]Somme d'une zone de texte
    Par acceso dans le forum IHM
    Réponses: 5
    Dernier message: 05/01/2006, 17h38
  4. [Jonas] Impossible de déployer une Entity Bean CMP2
    Par blockparty dans le forum JOnAS
    Réponses: 2
    Dernier message: 01/12/2005, 15h45
  5. Réponses: 4
    Dernier message: 05/10/2005, 16h07

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