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

Hibernate Java Discussion :

annotation primary key


Sujet :

Hibernate Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    109
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2006
    Messages : 109
    Par défaut annotation primary key
    J'essaye d'utiliser hibernate avec le mécanisme d'annotation.

    Voici le code de ma classe

    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
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package fr.aef.util;
     
    import java.io.Serializable;
    import java.util.GregorianCalendar;
    import javax.persistence.Column;
    import javax.persistence.Embedded;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Inheritance;
    import javax.persistence.InheritanceType;
    import javax.persistence.Table;
     
    /**
     *
     * @author ratatouille
     */
    @Entity
    @Table(name="UTILISATEURS")
    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
    public class CompteUtilisateur implements Serializable {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name = "ID")
        private Long id;
     
        @Column(name="NOM")
        private String nom;
     
        @Column(name="PRENOM")
        private String prenom;
     
        @Column(name="EMAIL")
        private String email;
    /*
        @Column(name="DATE_DE_NAISSANCE")
        private GregorianCalendar dateDeNaissance;
    /*
        @Embedded
        private Adresse adresse;
     
        @Embedded
        private Telephone telephone;
    */
        public String getEmail() {
            return email;
        }
     
        public void setEmail(String email) {
            this.email = email;
        }
     
    /*
        public void setAdresse(Adresse adresse) {
            this.adresse = adresse;
        }
    */
     /*   public void setDateDeNaissance(GregorianCalendar dateDeNaissance) {
            this.dateDeNaissance = dateDeNaissance;
        }
    */
        public void setNom(String nom) {
            if( nom == null )
                 throw new IllegalArgumentException();
            this.nom = nom;
        }
     
        public void setPrenom(String prenom) {
            if( prenom == null)
                 throw new IllegalArgumentException();
            this.prenom = prenom;
        }
    /*
        public void setTelephone(Telephone telephone) {
            this.telephone = telephone;
        }
     
        public Adresse getAdresse() {
            return adresse;
        }
    */
     /*   public GregorianCalendar getDateDeNaissance() {
            return dateDeNaissance;
        }
    */
        public String getNom() {
            return nom;
        }
     
        public String getPrenom() {
            return prenom;
        }
     
      /*  public Telephone getTelephone() {
            return telephone;
        }
    */
        public Long getId() {
            return id;
        }
     
        public void setId(Long id) {
            this.id = id;
        }
     
        public CompteUtilisateur(String nom, String prenom)
        {
            if( nom == null || prenom == null )
                throw new IllegalArgumentException();
     
            this.nom = nom;
            this.prenom = prenom;
        }
     
     
        public CompteUtilisateur() {
        }
     
     
    }
    Lorsque je créé une instance de l'objet compteUtilisateur, le champ id est nul.
    lorsque je fais

    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
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package fr.aef.services;
     
    import fr.aef.util.CompteUtilisateur;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.Persistence;
     
    /**
     *
     * @author ratatouille
     */
    public class CompteManager {
     
        public CompteManager()
        {
     
        }
     
        public void creerUnCompte( CompteUtilisateur compte )
        {
          if( compte == null )
                    throw new IllegalArgumentException();
     
                EntityManagerFactory emf;
                EntityManager em;
                EntityTransaction tx;
     
                emf = Persistence.createEntityManagerFactory("AnnuaireEntrepreneursPU");
                em = emf.createEntityManager();
                tx = em.getTransaction();
     
                try
                {
     
                    tx.begin();
                    em.persist(compte);
                    tx.commit();
                }
                catch(Exception e )
                {
                    System.out.println( e.toString() );
                }
                finally
                {
                    if (tx.isActive())
                    {
                        tx.rollback();
                    }
                    em.close();
                }
            }
    }
    J'ai l'erreur suivante :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    exporting generated schema to database
    schema export complete
    SQL Error: -1, SQLState: 23502
    La colonne 'ID' ne peut pas accepter de valeur NULL.
    javax.persistence.EntityExistsException: org.hibernate.exception.ConstraintViolationException: could not insert: [fr.aef.util.CompteUtilisateur]
    Si vous avez un lien pour l'utilisation de Hibernate avec des annotations, je suis preneur .

    Merci

  2. #2
    Membre confirmé
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    109
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2006
    Messages : 109
    Par défaut
    J'ai toujours pas trouvé la solution. Je me suis dit que j'utilisais peut etre mal les annotations et comme je n'arrivais pas à trouver de doc sur internet je suis passé par des fichiers XML mais j'ai toujours la même erreur :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    Not binding factory to JNDI, no JNDI name configured
    Running hbm2ddl schema export
    exporting generated schema to database
    Unsuccessful: create table UTILISATEURS (LONG_ID bigint generated by default as identity (start with 1), nom varchar(255), prenom varchar(255), primary key (LONG_ID))
    Table/View 'UTILISATEURS' existe déjà dans Schema 'ADMIN'.
    schema export complete
    Hibernate: insert into UTILISATEURS (LONG_ID, nom, prenom) values (null, ?, ?)
    SQL Error: -1, SQLState: 23502
    La colonne 'LONG_ID' ne peut pas accepter de valeur NULL.

    Je n'arrive pas à faire générer ma clé à hibernate. Voici les fichiers utilisés. Est ce que quelqu'un a une idée svp ?

    CompteUtilisateur.hbm.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping package="fr.aef.util">
      <class name="CompteUtilisateur" table="UTILISATEURS" >
         <id name="id" column="LONG_ID">
                <generator class="native"/>
         </id>
         <property name="nom"/>
         <property name="prenom"/>
      </class>
    </hibernate-mapping>
    CompteUtilisateur.java
    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
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package fr.aef.util;
     
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.Id;
     
    /**
     *
     * @author ratatouille
     */
    @Entity
    public class CompteUtilisateur implements Serializable {
     
        private static final long serialVersionUID = -1831662765296246807L;
     
     
        @Id
        private Long id;
     
     
        private String nom;
     
     
        private String prenom;
     
     
        private String email;
    /*
        @Column(name="DATE_DE_NAISSANCE")
        private GregorianCalendar dateDeNaissance;
    /*
        @Embedded
        private Adresse adresse;
     
        @Embedded
        private Telephone telephone;
    */
        public String getEmail() {
            return email;
        }
     
        public void setEmail(String email) {
            this.email = email;
        }
     
    /*
        public void setAdresse(Adresse adresse) {
            this.adresse = adresse;
        }
    */
     /*   public void setDateDeNaissance(GregorianCalendar dateDeNaissance) {
            this.dateDeNaissance = dateDeNaissance;
        }
    */
        public void setNom(String nom) {
            if( nom == null )
                 throw new IllegalArgumentException();
            this.nom = nom;
        }
     
        public void setPrenom(String prenom) {
            if( prenom == null)
                 throw new IllegalArgumentException();
            this.prenom = prenom;
        }
    /*
        public void setTelephone(Telephone telephone) {
            this.telephone = telephone;
        }
     
        public Adresse getAdresse() {
            return adresse;
        }
    */
     /*   public GregorianCalendar getDateDeNaissance() {
            return dateDeNaissance;
        }
    */
        public String getNom() {
            return nom;
        }
     
        public String getPrenom() {
            return prenom;
        }
     
      /*  public Telephone getTelephone() {
            return telephone;
        }
    */
     
        public Long getId() {
            return id;
        }
     
        public void setId(Long id) {
            this.id = id;
        }
     
        public CompteUtilisateur() {
        }
     
     
    }
    hibernate.cfg.xml
    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
     
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
      <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
        <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
        <property name="hibernate.connection.url">jdbc:derby://localhost:1527/AnnuaireEntrepreneursDB</property>
        <property name="hibernate.connection.username">admin</property>
        <property name="hibernate.connection.password">adminadmin</property>
     
         <!-- JDBC connection pool (use the built-in) -->
         <property name="connection.pool_size">1</property>
     
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>
     
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
     
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
     
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
     
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
     
        <mapping resource="fr/aef/util/CompteUtilisateur.hbm.xml"/>
     
      </session-factory>
    </hibernate-configuration>

  3. #3
    Membre confirmé
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    109
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2006
    Messages : 109
    Par défaut
    J'ai changé mon fichier CompteUtilisateur.hbm.xml en :

    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
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping package="fr.aef.util">
      <class name="CompteUtilisateur" table="UTILISATEURS" >
         <id name="id" column="LONG_ID">
                <generator class="org.hibernate.id.TableHiLoGenerator">
                    <param name="table">hi_value</param>
                    <param name="column">next_value</param>
                </generator>
     
         </id>
         <property name="nom"/>
         <property name="prenom"/>
      </class>
    </hibernate-mapping>
    Et ca marche. Je vais essayer de refaire ca en annotation

  4. #4
    Membre confirmé
    Profil pro
    Inscrit en
    Juin 2006
    Messages
    109
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2006
    Messages : 109
    Par défaut
    Pour l'injection il faut faire :
    - dans le HibernateUtil un :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
     return new AnnotationConfiguration().configure().buildSessionFactory();
    au lieu de
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
     return new Configuration().configure().buildSessionFactory();

    Dans hibernate.cfg.xml, il faut faire pour indiquer quelle classes sont utilisées
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    <mapping class="fr.aef.util.CompteUtilisateur"/>

    et ma classe CompteUtilisateur est :

    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
     
    @Entity
    @Table(name="UTILISATEURS")
    public class CompteUtilisateur implements Serializable {
     
        private static final long serialVersionUID = -1831662765296246807L;
     
     
        @javax.persistence.TableGenerator(
           name="empGen",
                table="ID_GEN",
                pkColumnName="GEN_KEY",
                valueColumnName="GEN_VALUE",
                pkColumnValue="EMP_ID",
                allocationSize=1)
        @Id
        @GeneratedValue(strategy=GenerationType.TABLE ,generator="empGen")
        @Column( name="LONG_ID")
        private Long id;
     
        @Column( name="NOM")
        private String nom;
     
        @Column( name="PRENOM")
        private String prenom;
     
        @Column( name="EMAIL")
        private String email;
    /*
        @Column(name="DATE_DE_NAISSANCE")
        private GregorianCalendar dateDeNaissance;
    /*
        @Embedded
        private Adresse adresse;
     
        @Embedded
        private Telephone telephone;
    */
        public String getEmail() {
            return email;
        }
     
        public void setEmail(String email) {
            this.email = email;
        }
     
    /*
        public void setAdresse(Adresse adresse) {
            this.adresse = adresse;
        }
    */
     /*   public void setDateDeNaissance(GregorianCalendar dateDeNaissance) {
            this.dateDeNaissance = dateDeNaissance;
        }
    */
        public void setNom(String nom) {
            if( nom == null )
                 throw new IllegalArgumentException();
            this.nom = nom;
        }
     
        public void setPrenom(String prenom) {
            if( prenom == null)
                 throw new IllegalArgumentException();
            this.prenom = prenom;
        }
    /*
        public void setTelephone(Telephone telephone) {
            this.telephone = telephone;
        }
     
        public Adresse getAdresse() {
            return adresse;
        }
    */
     /*   public GregorianCalendar getDateDeNaissance() {
            return dateDeNaissance;
        }
    */
        public String getNom() {
            return nom;
        }
     
        public String getPrenom() {
            return prenom;
        }
     
      /*  public Telephone getTelephone() {
            return telephone;
        }
    */
     
        public Long getId() {
            return id;
        }
     
        public void setId(Long id) {
            this.id = id;
        }
     
        public CompteUtilisateur() {
        }
     
     
    }

    J'espère que ca pourra aider certains qui débutent sous hibernate

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

Discussions similaires

  1. [ODBC] Recherche du champ qui est Primary Key
    Par XtofRoland dans le forum PHP & Base de données
    Réponses: 3
    Dernier message: 07/02/2006, 11h43
  2. PRIMARY KEY - UNIQUE - INDEX
    Par Thierry8 dans le forum Requêtes
    Réponses: 4
    Dernier message: 16/12/2005, 23h28
  3. pb de primary key sur 2 colonnes
    Par new_wave dans le forum Designer
    Réponses: 14
    Dernier message: 25/11/2005, 11h05
  4. DROP PRIMARY KEY
    Par popopopo dans le forum Langage SQL
    Réponses: 2
    Dernier message: 04/08/2005, 11h11
  5. BDD, r-a-z index et indice primary key ?
    Par lord_paco dans le forum MS SQL Server
    Réponses: 9
    Dernier message: 11/07/2003, 10h24

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