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 :

[EJB3] problèmes annotations


Sujet :

JPA Java

  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France, Yvelines (Île de France)

    Informations forums :
    Inscription : Juin 2007
    Messages : 2
    Points : 2
    Points
    2
    Par défaut [EJB3] problèmes annotations
    Bonjour à tous,
    Je suis un débutant sur les ejb et je dois faire un projet (un site qui dynamique qui permet de gérer une base de données) et pour cela j'aurai besoin de récupérer le nom des colonnes de mes tables pour faire mes formulaires. Je pensais les récupérer à l'aides des annotations contenues dans la classe de ma table mais je rencontre un problème c'est que je n'obtiens qu'une partie des annotations et malheureusement pour pas celle qui m'intéresse.

    j'utilise le code suivant pour récupérer les annotations.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    Annotation[] test =actor.getClass().getAnnotations();
    for(int i=0;i<test.length;i++)
    {
      System.out.println(test[i].toString());
    }
    Et voilà le résultat que j'obtiens.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    @javax.persistence.Entity(name=)
    @javax.persistence.NamedQueries(value=[@javax.persistence.NamedQuery(hints=[], name=Actor.findByActorId, query=SELECT a FROM Actor a WHERE a.actorId = :actorId), @javax.persistence.NamedQuery(hints=[], name=Actor.findByFirstName, query=SELECT a FROM Actor a WHERE a.firstName = :firstName), @javax.persistence.NamedQuery(hints=[], name=Actor.findByLastName, query=SELECT a FROM Actor a WHERE a.lastName = :lastName), @javax.persistence.NamedQuery(hints=[], name=Actor.findByLastUpdate, query=SELECT a FROM Actor a WHERE a.lastUpdate = :lastUpdate)])
    @javax.persistence.Table(uniqueConstraints=[], catalog=, schema=, name=actor)

    Donc voici ma class Actor qui a été généré automatiquement à partir de la table actor de ma base de donnée
    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
    package data;
     
    import java.io.Serializable;
    import java.util.Collection;
    import java.util.Date;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
     
    /**
     * Entity class Actor
     * 
     * @author Fabien
     */
    @Entity
    @Table(name = "actor")
    @NamedQueries( {
            @NamedQuery(name = "Actor.findByActorId", query = "SELECT a FROM Actor a WHERE a.actorId = :actorId"),
            @NamedQuery(name = "Actor.findByFirstName", query = "SELECT a FROM Actor a WHERE a.firstName = :firstName"),
            @NamedQuery(name = "Actor.findByLastName", query = "SELECT a FROM Actor a WHERE a.lastName = :lastName"),
            @NamedQuery(name = "Actor.findByLastUpdate", query = "SELECT a FROM Actor a WHERE a.lastUpdate = :lastUpdate")
        })
    public class Actor implements Serializable {
     
        @Id
        @Column(name = "actor_id", nullable = false)
        private Short actorId;
     
        @Column(name = "first_name", nullable = false)
        private String firstName;
     
        @Column(name = "last_name", nullable = false)
        private String lastName;
     
        @Column(name = "last_update")
        @Temporal(TemporalType.TIMESTAMP)
        private Date lastUpdate;
     
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "actor")
        private Collection<FilmActor> filmActorCollection;
     
        /** Creates a new instance of Actor */
        public Actor() {
        }
     
        /**
         * Creates a new instance of Actor with the specified values.
         * @param actorId the actorId of the Actor
         */
        public Actor(Short actorId) {
            this.actorId = actorId;
        }
     
        /**
         * Creates a new instance of Actor with the specified values.
         * @param actorId the actorId of the Actor
         * @param firstName the firstName of the Actor
         * @param lastName the lastName of the Actor
         */
        public Actor(Short actorId, String firstName, String lastName) {
            this.actorId = actorId;
            this.firstName = firstName;
            this.lastName = lastName;
        }
     
        /**
         * Gets the actorId of this Actor.
         * @return the actorId
         */
        public Short getActorId() {
            return this.actorId;
        }
     
        /**
         * Sets the actorId of this Actor to the specified value.
         * @param actorId the new actorId
         */
        public void setActorId(Short actorId) {
            this.actorId = actorId;
        }
     
        /**
         * Gets the firstName of this Actor.
         * @return the firstName
         */
        public String getFirstName() {
            return this.firstName;
        }
     
        /**
         * Sets the firstName of this Actor to the specified value.
         * @param firstName the new firstName
         */
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
     
        /**
         * Gets the lastName of this Actor.
         * @return the lastName
         */
        public String getLastName() {
            return this.lastName;
        }
     
        /**
         * Sets the lastName of this Actor to the specified value.
         * @param lastName the new lastName
         */
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
     
        /**
         * Gets the lastUpdate of this Actor.
         * @return the lastUpdate
         */
        public Date getLastUpdate() {
            return this.lastUpdate;
        }
     
        /**
         * Sets the lastUpdate of this Actor to the specified value.
         * @param lastUpdate the new lastUpdate
         */
        public void setLastUpdate(Date lastUpdate) {
            this.lastUpdate = lastUpdate;
        }
     
        /**
         * Gets the filmActorCollection of this Actor.
         * @return the filmActorCollection
         */
        public Collection<FilmActor> getFilmActorCollection() {
            return this.filmActorCollection;
        }
     
        /**
         * Sets the filmActorCollection of this Actor to the specified value.
         * @param filmActorCollection the new filmActorCollection
         */
        public void setFilmActorCollection(Collection<FilmActor> filmActorCollection) {
            this.filmActorCollection = filmActorCollection;
        }
     
        /**
         * Returns a hash code value for the object.  This implementation computes 
         * a hash code value based on the id fields in this object.
         * @return a hash code value for this object.
         */
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (this.actorId != null ? this.actorId.hashCode() : 0);
            return hash;
        }
     
        /**
         * Determines whether another object is equal to this Actor.  The result is 
         * <code>true</code> if and only if the argument is not null and is a Actor object that 
         * has the same id field values as this object.
         * @param object the reference object with which to compare
         * @return <code>true</code> if this object is the same as the argument;
         * <code>false</code> otherwise.
         */
        @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 Actor)) {
                return false;
            }
            Actor other = (Actor)object;
            if (this.actorId != other.actorId && (this.actorId == null || !this.actorId.equals(other.actorId))) return false;
            return true;
        }
     
        /**
         * Returns a string representation of the object.  This implementation constructs 
         * that representation based on the id fields.
         * @return a string representation of the object.
         */
        @Override
        public String toString() {
            return "data.Actor[actorId=" + actorId + "]";
        }
     
    }
    Donc si quelqu'un pouvait me renseigner sur la manière que je peux utiliser pour récupérer mes annotations Column ça me serait très utile.

    Merci d'avance pour votre aide

  2. #2
    Membre à l'essai
    Inscrit en
    Avril 2007
    Messages
    34
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 34
    Points : 14
    Points
    14
    Par défaut
    Citation Envoyé par loco_crazy
    Donc voici ma class Actor qui a été généré automatiquement à partir de la table actor de ma base de donnée
    salut, désolé c'est pas la solution mais une question..

    comment tu fais pour générer un entity bean à partir d'une table d'une BD?

    merci

  3. #3
    Expert confirmé
    Avatar de Valère
    Profil pro
    Inscrit en
    Août 2005
    Messages
    1 334
    Détails du profil
    Informations personnelles :
    Âge : 49
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Août 2005
    Messages : 1 334
    Points : 4 740
    Points
    4 740
    Par défaut
    Citation Envoyé par kuruma45
    salut, désolé c'est pas la solution mais une question..

    comment tu fais pour générer un entity bean à partir d'une table d'une BD?

    merci
    Bonjour kuruma45,

    Ca resemble fortement à du code généré par Netbeans 5.5+, regarde http://www.netbeans.org/kb/55/persistence-j2se.html

    Valère
    Pensez au bouton
    Je ne répond pas aux questions techniques par email ou MP.

  4. #4
    Expert confirmé
    Avatar de Valère
    Profil pro
    Inscrit en
    Août 2005
    Messages
    1 334
    Détails du profil
    Informations personnelles :
    Âge : 49
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Août 2005
    Messages : 1 334
    Points : 4 740
    Points
    4 740
    Par défaut
    Citation Envoyé par loco_crazy
    Bonjour à tous,

    Donc si quelqu'un pouvait me renseigner sur la manière que je peux utiliser pour récupérer mes annotations Column ça me serait très utile.

    Merci d'avance pour votre aide
    Ce qui se passe, c'est que tu appliques ta méthode getAnnotations à ta classe, et elle te répond bien tout ce qui a été défini (tu as bien tes 4 NamedQuery, seule la mise en forme est un peut différente.

    Si tu veux obtenir les annotation de tes colonnes, il faut aller plus loin dans l'introspection de ta classe:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
            Field[] fields = this.getClass().getDeclaredFields();
            for (Field elem : fields) {
                System.out.println("Field: " + elem.getName() + "\tAnnotation: " + elem.getAnnotations().toString());
            }
    Valère
    Pensez au bouton
    Je ne répond pas aux questions techniques par email ou MP.

  5. #5
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2003
    Messages
    79
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2003
    Messages : 79
    Points : 89
    Points
    89
    Par défaut
    @ kuruma45
    Le plus simple c'est d'utiliser par exemple NetBeans 5.5, là tu va pouvoir facilement lancer le générateur de EntityBean;
    Il faut juste que tu configures ta base de données dans netbeans et puis new EntityBean from database.


    @ loco_crazy
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    Class<?> clazz=Class.forName(args[0]);
    Object obj=clazz.newInstance();
    for(Field field:clazz.getFields()) {
    System.out.println("field "+field.getName()+" "+field.get(obj));
    }
    ps: flute Valered est passé avant moi :-) oui la différence entre son code et le mien c'est que le sien je pense n'a pas besoin d'instancier un objet de la classe, moi bien.

  6. #6
    Expert confirmé
    Avatar de Valère
    Profil pro
    Inscrit en
    Août 2005
    Messages
    1 334
    Détails du profil
    Informations personnelles :
    Âge : 49
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations forums :
    Inscription : Août 2005
    Messages : 1 334
    Points : 4 740
    Points
    4 740
    Par défaut
    Moi je travaillais sur la classe this, elle est formément déjà instanciée .

    L'essentiel est d'avoir mis loco_crazy sur la piste.

    Val
    Pensez au bouton
    Je ne répond pas aux questions techniques par email ou MP.

  7. #7
    Membre à l'essai
    Inscrit en
    Avril 2007
    Messages
    34
    Détails du profil
    Informations forums :
    Inscription : Avril 2007
    Messages : 34
    Points : 14
    Points
    14
    Par défaut
    c'est bien ce qu'il me semblait j'avais déjà lu un truc la dessus mais j'y croyais pas trop...

    En gros je suis passé du dev avec netbeans, puis avec les EJB, je suis passer à Eclipse!!!! JBOSSIDE et autres....

    donc faut que je retourne aux sources

    merci pour ce tuyau les gars

  8. #8
    Candidat au Club
    Profil pro
    Inscrit en
    Juin 2007
    Messages
    2
    Détails du profil
    Informations personnelles :
    Localisation : France, Yvelines (Île de France)

    Informations forums :
    Inscription : Juin 2007
    Messages : 2
    Points : 2
    Points
    2
    Par défaut
    Bonjour, merci de vos réponses

    j'ai un ami qui m'a donné cette solution

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     Class mClass = Class.forName ("data.Actor");
    for (Field field : mClass.getDeclaredFields())
          {
            System.out.println(field);
            Annotation colonne = field.getAnnotation(javax.persistence.Column.class);
            if (colonne != null)
            {
              System.out.println(" =====> Colonne : " + field.getName());
            }
          }
    Mais je vais quand même étudier vos solutions.

    A +

  9. #9
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2003
    Messages
    79
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Mars 2003
    Messages : 79
    Points : 89
    Points
    89
    Par défaut
    c'est la même chose, si ce n'est qu'il y a une comparaison supplémentaire avec l'annotation persistante Column

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

Discussions similaires

  1. [Struts][Hibernate][EJB3]Problème d'intégration EJB 3.0
    Par midoENSI dans le forum Struts 1
    Réponses: 2
    Dernier message: 31/05/2007, 11h17
  2. [EJB3] problème d'intéraction avec la BDD
    Par toomsounet dans le forum Wildfly/JBoss
    Réponses: 1
    Dernier message: 15/03/2007, 00h08
  3. [EJB3] novice: annotation j2EE coté client
    Par brieuc_guez dans le forum JPA
    Réponses: 2
    Dernier message: 22/01/2007, 21h34
  4. Réponses: 7
    Dernier message: 21/01/2007, 12h12
  5. [EJB3] problème de fetch=lazy avec ejb3
    Par pbdlpc dans le forum JPA
    Réponses: 2
    Dernier message: 16/01/2007, 21h52

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