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

Persistance des données Java Discussion :

Mapper sa base de données avec le pattern DAO [Tutoriel]


Sujet :

Persistance des données Java

  1. #1
    Membre habitué Avatar de cysboy
    Profil pro
    Développeur informatique
    Inscrit en
    Août 2006
    Messages
    221
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Août 2006
    Messages : 221
    Points : 168
    Points
    168
    Par défaut Mapper sa base de données avec le pattern DAO
    Bonjour à toutes et tous !

    Je viens de terminer un tuto sur l'utilisation du pattern DAO.

    Vu que ce pattern permet d'encapsuler la façon dont un programme récupère les données d'un systèmes de stockage (fichier, BDD...), un exemple avec une base de données était de mise.
    Nous allons aussi voir comment associer ce pattern avec le pattern Factory afin de pouvoir utiliser plusieurs systèmes de stockage.

    Quelques pré-requis sont toutefois nécessaire : savoir utiliser JDBC !

    D'avance merci pour vos commentaires.

  2. #2
    Inactif  
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    2 189
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2006
    Messages : 2 189
    Points : 2 336
    Points
    2 336
    Par défaut
    Hello,

    Pour une utilisation simple sans ORM c'est tout à fait concevable et même très bien définit pour.

    Mais pour de l'Hibernate, TopLink ou autre JDO c'est pas possible.

    Et pour la représentation en en tant que String tu peux utilisé ceci

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    /**
             * Make a String representation of the current object
             */
    	@Override
    	public String toString() {
    		return ToStringBuilder.reflectionToString(this);
    	}

  3. #3
    Membre confirmé Avatar de toomsounet
    Profil pro
    Inscrit en
    Janvier 2005
    Messages
    481
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2005
    Messages : 481
    Points : 576
    Points
    576
    Par défaut
    Merci pour ce tutoriel, c'est toujours bon de commencer par là avant de se pencher vers un ORM.
    "Most Java programs are so rife with concurrency bugs that they work only by accident"

  4. #4
    Membre du Club
    Profil pro
    Inscrit en
    Juillet 2002
    Messages
    73
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juillet 2002
    Messages : 73
    Points : 57
    Points
    57
    Par défaut
    Bonjour

    Une question à propos de ce tutoriel :
    Le pattern singleton est utilisé afin d'instancier la connexion à la base de données. Est ce que dans le cas d'une appli web il est judicieux d'utiliser ce pattern ?

  5. #5
    Membre régulier
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Février 2007
    Messages
    68
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Opérateur de télécommunications

    Informations forums :
    Inscription : Février 2007
    Messages : 68
    Points : 85
    Points
    85
    Par défaut
    Citation Envoyé par korrigan Voir le message
    Bonjour

    Une question à propos de ce tutoriel :
    Le pattern singleton est utilisé afin d'instancier la connexion à la base de données. Est ce que dans le cas d'une appli web il est judicieux d'utiliser ce pattern ?
    Non, il faudrait utiliser un pool de connexion

  6. #6
    Nouveau membre du Club
    Profil pro
    Poste x dans une société
    Inscrit en
    Mars 2007
    Messages
    27
    Détails du profil
    Informations personnelles :
    Localisation : Algérie

    Informations professionnelles :
    Activité : Poste x dans une société

    Informations forums :
    Inscription : Mars 2007
    Messages : 27
    Points : 38
    Points
    38
    Par défaut
    Merci pour ce tuto , Mais Concernant le code source , Est ce qu'il n'y a pas de méthode pour le générer automatiquement (un plugin eclipse par exemple) ?
    Parce que pour une BD contenant plus de 100 Tables on doit ecrire au moin
    (100 x 2) Classes ? Merci .

  7. #7
    Inactif  
    Profil pro
    Inscrit en
    Mai 2006
    Messages
    2 189
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : Suisse

    Informations forums :
    Inscription : Mai 2006
    Messages : 2 189
    Points : 2 336
    Points
    2 336
    Par défaut
    Citation Envoyé par khaledUSTHB Voir le message
    Merci pour ce tuto , Mais Concernant le code source , Est ce qu'il n'y a pas de méthode pour le générer automatiquement (un plugin eclipse par exemple) ?
    Parce que pour une BD contenant plus de 100 Tables on doit ecrire au moin
    (100 x 2) Classes ? Merci .
    à ma connaissance aucun plugin ne génère de dao uniquement basé sur une bd mise à part dans l'utilisation de hibernate si tu veux hibernate utilise myeclipse c'est pas chère ...

  8. #8
    Nouveau Candidat au Club
    Inscrit en
    Juin 2009
    Messages
    1
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Merci
    Merci pour ce tutoriel, l'exemple est simple et claire, il m'a beaucoup servi

  9. #9
    Membre du Club
    Inscrit en
    Juin 2009
    Messages
    61
    Détails du profil
    Informations forums :
    Inscription : Juin 2009
    Messages : 61
    Points : 48
    Points
    48
    Par défaut
    Bon tutorial dans l'ensemble mais sur les codes d'exemples les objets "Factory" sont utilisés avant même que la notion de "Factory" soit introduite donc on ne peut pas compiler pour faire les premiers tests. Il faut lire le tutorial en entier pour arriver à faire quelques choses.

    Pour ce qui est d'Hibernate il faut quand même décrire la base de données au format XML et c'est assez fastidieux lorsque l'on a beaucoup de tables, notamment des tables de jointure.

  10. #10
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Novembre 2008
    Messages
    59
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2008
    Messages : 59
    Points : 26
    Points
    26
    Par défaut
    Bonjour!!! merci pour ce tuto mais comme le message ci-dessus le dit : la méthode d'apprentissage progressive ne peut pas s'appliquer quelqu'un peu m'expliquer comment faire sans "Factory" ou si c'est pas possible m'expliquer ce qu'il y a à comprendre...?
    J'ai du mal à faire la part des choses quand les testes ne marchent pas et surtout ne peuvent pas marcher

    s'il suffit de mettre les lignes en commentaires ou je sais pas quoi d'autre dites le moi c'est tout nouveau pour moi les concepts comme ça j'aimerai bien comprendre. Merci

  11. #11
    Expert éminent
    Avatar de _skip
    Homme Profil pro
    Développeur d'applications
    Inscrit en
    Novembre 2005
    Messages
    2 898
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur d'applications
    Secteur : High Tech - Produits et services télécom et Internet

    Informations forums :
    Inscription : Novembre 2005
    Messages : 2 898
    Points : 7 752
    Points
    7 752
    Par défaut
    Alors au risque de passer le gros vilain méchant :

    Quand je vois ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    .executeUpdate(
                    	"UPDATE developpeur SET dev_nom = '" + obj.getNom() + "',"+
                    	" dev_prenom = '" + obj.getPrenom() + "',"+
                    	" dev_lan_k = '" + obj.getLangage().getId() + "'"+
                    	" WHERE dev_id = " + obj.getId()
                     );
    Je me dis que c'est à corriger quand même, c'est un truc qui se ne se fait pas de bricoler des requêtes par concaténation de bouts de morceau de trucs . On utilise des requêtes paramétrées.


    En plus ça

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    } catch (SQLException e) {
    	            e.printStackTrace();
    	    }
    C'est de très loin pas suffisant comme gestion d'erreur, toutes tes requêtes font un échec silencieux et retourne des valeurs à la noix ce qui est le pire antipattern imaginable en terme de gestion d'exception.

    Et aussi, le pattern session-per-application qui est utilisé pour la connexion au SGBD est lui aussi une méthode très peu recommendable.

    Puis pourquoi utiliser des resultSet updatable alors que forward_only suffit largement? Es-tu sûr du bien-fondé de ce choix?

  12. #12
    Membre averti
    Profil pro
    Inscrit en
    Mars 2008
    Messages
    338
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Mars 2008
    Messages : 338
    Points : 402
    Points
    402
    Par défaut
    C'est une bonne initiative, mais je trouve que ton exemple n'est pas vraiment pratique, ce n'est pas générique, la classe DAO<T> n'apporte aucune factorisation et je ne vois pas sa réutilisation!! Il faut autant de classes DAO que de classes métier, et on est obligé d'implémenter des méthodes que parfois on en a pas vraiment besoin (si un objet n'est pas updatable par exemple).
    Gestion des exceptions quasi nulle comme l'a dit _skip.

  13. #13
    Candidat au Club
    Inscrit en
    Juillet 2010
    Messages
    4
    Détails du profil
    Informations forums :
    Inscription : Juillet 2010
    Messages : 4
    Points : 4
    Points
    4
    Par défaut
    Citation Envoyé par _skip Voir le message
    Alors au risque de passer le gros vilain méchant :

    Quand je vois ça :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    .executeUpdate(
                    	"UPDATE developpeur SET dev_nom = '" + obj.getNom() + "',"+
                    	" dev_prenom = '" + obj.getPrenom() + "',"+
                    	" dev_lan_k = '" + obj.getLangage().getId() + "'"+
                    	" WHERE dev_id = " + obj.getId()
                     );
    Je me dis que c'est à corriger quand même, c'est un truc qui se ne se fait pas de bricoler des requêtes par concaténation de bouts de morceau de trucs . On utilise des requêtes paramétrées.


    En plus ça

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    } catch (SQLException e) {
    	            e.printStackTrace();
    	    }
    C'est de très loin pas suffisant comme gestion d'erreur, toutes tes requêtes font un échec silencieux et retourne des valeurs à la noix ce qui est le pire antipattern imaginable en terme de gestion d'exception.

    Et aussi, le pattern session-per-application qui est utilisé pour la connexion au SGBD est lui aussi une méthode très peu recommendable.

    Puis pourquoi utiliser des resultSet updatable alors que forward_only suffit largement? Es-tu sûr du bien-fondé de ce choix?


    je sais pas comment on peut gérer les sessions avec Pattern DAO ???

    j utlise JSP et Struts pour les couche Vue et controller.


    Merrrrrci bien

  14. #14
    Futur Membre du Club
    Inscrit en
    Août 2010
    Messages
    4
    Détails du profil
    Informations forums :
    Inscription : Août 2010
    Messages : 4
    Points : 5
    Points
    5
    Par défaut update Societe
    C'est bien comme introduction à DAO, sinon pour la gestion d'exception ou autres, je pense que c'est pas obligatoire lorsque le code ne serait qu'un exemple d'une introduction.

    Pour la mise à jour de société, vous mettez à jour les attributs de l'object et aussi les objects de Developpeur en relation, ça c'est exact. Mais vous faites à chaque maj insert dans la table de relation entre Societe et Developpeur ce qui me semble illogique et faux.

  15. #15
    Membre régulier
    Inscrit en
    Février 2011
    Messages
    90
    Détails du profil
    Informations forums :
    Inscription : Février 2011
    Messages : 90
    Points : 83
    Points
    83
    Par défaut
    Bonjour,

    j'utilise le pattern DAO et trois cas se présentent dans mon cas:
    1) une table qui n'a pas de foreign key. ceci fonctionne parfaitement. voici les codes pour l'objet métier et l'objet DAO.

    ---- Objet métier :

    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
     
    package port_type_daogen;
     
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.math.*;
     
     
     
     
    public class Port_type implements Cloneable, Serializable {
     
     
        private int ID_Port_Type;
        private String Port_Type_Name;
        private int Port_Type_capacity;
     
     
     
     
     
        public Port_type () {
     
        }
     
        public Port_type (int ID_Port_TypeIn) {
     
              this.ID_Port_Type = ID_Port_TypeIn;
     
        }
     
     
     
        public int getID_Port_Type() {
              return this.ID_Port_Type;
        }
        public void setID_Port_Type(int ID_Port_TypeIn) {
              this.ID_Port_Type = ID_Port_TypeIn;
        }
     
        public String getPort_Type_Name() {
              return this.Port_Type_Name;
        }
        public void setPort_Type_Name(String Port_Type_NameIn) {
              this.Port_Type_Name = Port_Type_NameIn;
        }
     
        public int getPort_Type_capacity() {
              return this.Port_Type_capacity;
        }
        public void setPort_Type_capacity(int Port_Type_capacityIn) {
              this.Port_Type_capacity = Port_Type_capacityIn;
        }
     
     
     
     
        public void setAll(int ID_Port_TypeIn,
              String Port_Type_NameIn,
              int Port_Type_capacityIn) {
              this.ID_Port_Type = ID_Port_TypeIn;
              this.Port_Type_Name = Port_Type_NameIn;
              this.Port_Type_capacity = Port_Type_capacityIn;
        }
     
     
     
        public boolean hasEqualMapping(Port_type valueObject) {
     
              if (valueObject.getID_Port_Type() != this.ID_Port_Type) {
                        return(false);
              }
              if (this.Port_Type_Name == null) {
                        if (valueObject.getPort_Type_Name() != null)
                               return(false);
              } else if (!this.Port_Type_Name.equals(valueObject.getPort_Type_Name())) {
                        return(false);
              }
              if (valueObject.getPort_Type_capacity() != this.Port_Type_capacity) {
                        return(false);
              }
     
              return true;
        }
     
     
     
        public String toString() {
             StringBuffer out = new StringBuffer(this.getDaogenVersion());
            //StringBuffer out = new StringBuffer();
            out.append("\nclass Port_type, mapping to table port_type\n");
            out.append("Persistent attributes: \n");
            out.append("ID_Port_Type = " + this.ID_Port_Type + "\n");
            out.append("Port_Type_Name = " + this.Port_Type_Name + "\n");
            out.append("Port_Type_capacity = " + this.Port_Type_capacity + "\n");
            return out.toString();
        }
     
     
     
        public Object clone() {
            Port_type cloned = new Port_type();
     
            cloned.setID_Port_Type(this.ID_Port_Type);
            if (this.Port_Type_Name != null)
                 cloned.setPort_Type_Name(new String(this.Port_Type_Name));
            cloned.setPort_Type_capacity(this.Port_Type_capacity);
            return cloned;
        }
     
     
     
        public String getDaogenVersion() {
     
            return "**********************************";
        }
     
    }
    Voici l'objet DAO :

    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
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
     
    package port_type_daogen;
     
    import java.sql.*;
    import java.util.*;
    import java.math.*;
     
     
     
     
     
    public class Port_typeDao {
     
        // Cache contents:
        private boolean cacheOk;
        private List cacheData;
     
     
     
        public Port_typeDao() {
            resetCache();
        }
     
     
        public void resetCache() {
            cacheOk = false;
            cacheData = null;
        }
     
     
     
     
        public Port_type createValueObject() {
              return new Port_type();
        }
     
     
     
        public Port_type getObject(Connection conn, int ID_Port_Type) throws NotFoundException, SQLException {
     
              Port_type valueObject = createValueObject();
              valueObject.setID_Port_Type(ID_Port_Type);
              load(conn, valueObject);
              return valueObject;
        }
     
     
     
        public void load(Connection conn, Port_type valueObject) throws NotFoundException, SQLException {
     
              String sql = "SELECT * FROM port_type WHERE (ID_Port_Type = ? ) ";
              PreparedStatement stmt = null;
     
              try {
                   stmt = conn.prepareStatement(sql);
                   stmt.setInt(1, valueObject.getID_Port_Type());
     
                   singleQuery(conn, stmt, valueObject);
     
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
     
        public List loadAll(Connection conn) throws SQLException {
     
              // Check the cache status and use Cache if possible.
              if (cacheOk) {
                  return cacheData;
              }
     
              String sql = "SELECT * FROM port_type ORDER BY ID_Port_Type ASC ";
              List searchResults = listQuery(conn, conn.prepareStatement(sql));
     
              // Update cache and mark it ready.
              cacheData = searchResults;
              cacheOk = true;
     
              return searchResults;
        }
     
     
     
     
        public synchronized void create(Connection conn, Port_type valueObject) throws SQLException {
     
              String sql = "";
              PreparedStatement stmt = null;
              ResultSet result = null;
     
              try {
                   sql = "INSERT INTO port_type ( ID_Port_Type, Port_Type_Name, Port_Type_capacity) VALUES (?, ?, ?) ";
                   stmt = conn.prepareStatement(sql);
     
                   stmt.setInt(1, valueObject.getID_Port_Type());
                   stmt.setString(2, valueObject.getPort_Type_Name());
                   stmt.setInt(3, valueObject.getPort_Type_capacity());
     
                   int rowcount = databaseUpdate(conn, stmt);
                   if (rowcount != 1) {
                        //System.out.println("PrimaryKey Error when updating DB!");
                        throw new SQLException("PrimaryKey Error when updating DB!");
                   }
     
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
     
     
        }
     
     
     
        public void save(Connection conn, Port_type valueObject)
              throws NotFoundException, SQLException {
     
              String sql = "UPDATE port_type SET Port_Type_Name = ?, Port_Type_capacity = ? WHERE (ID_Port_Type = ? ) ";
              PreparedStatement stmt = null;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  stmt.setString(1, valueObject.getPort_Type_Name());
                  stmt.setInt(2, valueObject.getPort_Type_capacity());
     
                  stmt.setInt(3, valueObject.getID_Port_Type());
     
                  int rowcount = databaseUpdate(conn, stmt);
                  if (rowcount == 0) {
                       //System.out.println("Object could not be saved! (PrimaryKey not found)");
                       throw new NotFoundException("Object could not be saved! (PrimaryKey not found)");
                  }
                  if (rowcount > 1) {
                       //System.out.println("PrimaryKey Error when updating DB! (Many objects were affected!)");
                       throw new SQLException("PrimaryKey Error when updating DB! (Many objects were affected!)");
                  }
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
     
        public void delete(Connection conn, Port_type valueObject)
              throws NotFoundException, SQLException {
     
              String sql = "DELETE FROM port_type WHERE (ID_Port_Type = ? ) ";
              PreparedStatement stmt = null;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  stmt.setInt(1, valueObject.getID_Port_Type());
     
                  int rowcount = databaseUpdate(conn, stmt);
                  if (rowcount == 0) {
                       //System.out.println("Object could not be deleted (PrimaryKey not found)");
                       throw new NotFoundException("Object could not be deleted! (PrimaryKey not found)");
                  }
                  if (rowcount > 1) {
                       //System.out.println("PrimaryKey Error when updating DB! (Many objects were deleted!)");
                       throw new SQLException("PrimaryKey Error when updating DB! (Many objects were deleted!)");
                  }
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
     
        public void deleteAll(Connection conn) throws SQLException {
     
              String sql = "DELETE FROM port_type";
              PreparedStatement stmt = null;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  int rowcount = databaseUpdate(conn, stmt);
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
     
        public int countAll(Connection conn) throws SQLException {
     
              // Check the cache status and use Cache if possible.
              if (cacheOk) {
                  return cacheData.size();
              }
     
     
              String sql = "SELECT count(*) FROM port_type";
              PreparedStatement stmt = null;
              ResultSet result = null;
              int allRows = 0;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  result = stmt.executeQuery();
     
                  if (result.next())
                      allRows = result.getInt(1);
              } finally {
                  if (result != null)
                      result.close();
                  if (stmt != null)
                      stmt.close();
              }
              return allRows;
        }
     
     
     
        public List searchMatching(Connection conn, Port_type valueObject) throws SQLException {
     
              List searchResults;
     
              boolean first = true;
              StringBuffer sql = new StringBuffer("SELECT * FROM port_type WHERE 1=1 ");
     
              if (valueObject.getID_Port_Type() != 0) {
                  if (first) { first = false; }
                  sql.append("AND ID_Port_Type = ").append(valueObject.getID_Port_Type()).append(" ");
              }
     
              if (valueObject.getPort_Type_Name() != null) {
                  if (first) { first = false; }
                  sql.append("AND Port_Type_Name LIKE '").append(valueObject.getPort_Type_Name()).append("%' ");
              }
     
              if (valueObject.getPort_Type_capacity() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Port_Type_capacity = ").append(valueObject.getPort_Type_capacity()).append(" ");
              }
     
     
              sql.append("ORDER BY ID_Port_Type ASC ");
     
              // Prevent accidential full table results.
              // Use loadAll if all rows must be returned.
              if (first)
                   searchResults = new ArrayList();
              else
                   searchResults = listQuery(conn, conn.prepareStatement(sql.toString()));
     
              return searchResults;
        }
     
     
     
        public String getDaogenVersion() {
            return "******************************";
        }
     
     
     
        protected int databaseUpdate(Connection conn, PreparedStatement stmt) throws SQLException {
     
              int result = stmt.executeUpdate();
     
              resetCache();
     
              return result;
        }
     
     
     
     
        protected void singleQuery(Connection conn, PreparedStatement stmt, Port_type valueObject)
              throws NotFoundException, SQLException {
     
              ResultSet result = null;
     
              try {
                  result = stmt.executeQuery();
     
                  if (result.next()) {
     
                       valueObject.setID_Port_Type(result.getInt("ID_Port_Type"));
                       valueObject.setPort_Type_Name(result.getString("Port_Type_Name"));
                       valueObject.setPort_Type_capacity(result.getInt("Port_Type_capacity"));
     
                  } else {
                        //System.out.println("Port_type Object Not Found!");
                        throw new NotFoundException("Port_type Object Not Found!");
                  }
              } finally {
                  if (result != null)
                      result.close();
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
     
        protected List listQuery(Connection conn, PreparedStatement stmt) throws SQLException {
     
              ArrayList searchResults = new ArrayList();
              ResultSet result = null;
     
              try {
                  result = stmt.executeQuery();
     
                  while (result.next()) {
                       Port_type temp = createValueObject();
     
                       temp.setID_Port_Type(result.getInt("ID_Port_Type"));
                       temp.setPort_Type_Name(result.getString("Port_Type_Name"));
                       temp.setPort_Type_capacity(result.getInt("Port_Type_capacity"));
     
                       searchResults.add(temp);
                  }
     
              } finally {
                  if (result != null)
                      result.close();
                  if (stmt != null)
                      stmt.close();
              }
     
              return (List)searchResults;
        }
     
     
    }
    2) une table qui contient un foriegn key vers une autre table. je suis arrivé à résoudre ce probème et voici les codes.

    Objet métier:

    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
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
     
    package port_type_daogen;
     
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.math.*;
     
     /**
      * Board_ref Value Object.
      * This class is value object representing database table board_ref
      * This class is intented to be used together with associated Dao object.
      */
     
     
     
    public class Board_ref implements Cloneable, Serializable {
     
        /**
         * Persistent Instance variables. This data is directly
         * mapped to the columns of database table.
         */
        private int ID_Board_Ref;
        private String Board_Ref;
        private String Board_Ref_Name;
        private Boardclass Board_Class =  new Boardclass();
        private int Board_Slothoused;
        private Port_type Board_Port_type1  = new Port_type();
        private int Board_Port_Type1_number;
        private Port_type Board_Port_type2  = new Port_type();
        private int Board_Port_Type2_number;
        private Port_type Board_Port_type3  = new Port_type();
        private int Board_Port_Type3_number;
        private int NeededService_Board;
        private Eng_rule_board_valid_slot Board_Slot_rule =  new Eng_rule_board_valid_slot();
     
     
     
        /**
         * Constructors. DaoGen generates two constructors by default.
         * The first one takes no arguments and provides the most simple
         * way to create object instance. The another one takes one
         * argument, which is the primary key of the corresponding table.
         */
     
        public Board_ref () {
     
        }
     
        public Board_ref (int ID_Board_RefIn) {
     
              this.ID_Board_Ref = ID_Board_RefIn;
     
        }
     
     
        /**
         * Get- and Set-methods for persistent variables. The default
         * behaviour does not make any checks against malformed data,
         * so these might require some manual additions.
         */
     
        public int getID_Board_Ref() {
              return this.ID_Board_Ref;
        }
        public void setID_Board_Ref(int ID_Board_RefIn) {
              this.ID_Board_Ref = ID_Board_RefIn;
        }
     
        public String getBoard_Ref() {
              return this.Board_Ref;
        }
        public void setBoard_Ref(String Board_RefIn) {
              this.Board_Ref = Board_RefIn;
        }
     
        public String getBoard_Ref_Name() {
              return this.Board_Ref_Name;
        }
        public void setBoard_Ref_Name(String Board_Ref_NameIn) {
              this.Board_Ref_Name = Board_Ref_NameIn;
        }
     
        public Boardclass getBoard_Class() {
              return this.Board_Class;
        }
        public void setBoard_Class(Boardclass Board_ClassIn) {
              this.Board_Class = Board_ClassIn;
        }
     
        public int getBoard_Slothoused() {
              return this.Board_Slothoused;
        }
        public void setBoard_Slothoused(int Board_SlothousedIn) {
              this.Board_Slothoused = Board_SlothousedIn;
        }
     
        public Port_type getBoard_Port_type1() {
              return this.Board_Port_type1;
        }
        public void setBoard_Port_type1(Port_type Board_Port_type1In) {
              this.Board_Port_type1 = Board_Port_type1In;
        }
     
        public int getBoard_Port_Type1_number() {
              return this.Board_Port_Type1_number;
        }
        public void setBoard_Port_Type1_number(int Board_Port_Type1_numberIn) {
              this.Board_Port_Type1_number = Board_Port_Type1_numberIn;
        }
     
        public Port_type getBoard_Port_type2() {
              return this.Board_Port_type2;
        }
        public void setBoard_Port_type2(Port_type Board_Port_type2In) {
              this.Board_Port_type2 = Board_Port_type2In;
        }
     
        public int getBoard_Port_Type2_number() {
              return this.Board_Port_Type2_number;
        }
        public void setBoard_Port_Type2_number(int Board_Port_Type2_numberIn) {
              this.Board_Port_Type2_number = Board_Port_Type2_numberIn;
        }
     
        public Port_type getBoard_Port_type3() {
              return this.Board_Port_type3;
        }
        public void setBoard_Port_type3(Port_type Board_Port_type3In) {
              this.Board_Port_type3 = Board_Port_type3In;
        }
     
        public int getBoard_Port_Type3_number() {
              return this.Board_Port_Type3_number;
        }
        public void setBoard_Port_Type3_number(int Board_Port_Type3_numberIn) {
              this.Board_Port_Type3_number = Board_Port_Type3_numberIn;
        }
     
        public int getNeededService_Board() {
              return this.NeededService_Board;
        }
        public void setNeededService_Board(int NeededService_BoardIn) {
              this.NeededService_Board = NeededService_BoardIn;
        }
     
        public Eng_rule_board_valid_slot getBoard_Slot_rule() {
              return this.Board_Slot_rule;
        }
        public void setBoard_Slot_rule(Eng_rule_board_valid_slot Board_Slot_ruleIn) {
              this.Board_Slot_rule = Board_Slot_ruleIn;
        }
     
     
     
        /**
         * setAll allows to set all persistent variables in one method call.
         * This is useful, when all data is available and it is needed to
         * set the initial state of this object. Note that this method will
         * directly modify instance variales, without going trough the
         * individual set-methods.
         */
     
        public void setAll(int ID_Board_RefIn,
              String Board_RefIn,
              String Board_Ref_NameIn,
              Boardclass Board_ClassIn,
              int Board_SlothousedIn,
              Port_type Board_Port_type1In,
              int Board_Port_Type1_numberIn,
              Port_type Board_Port_type2In,
              int Board_Port_Type2_numberIn,
              Port_type Board_Port_type3In,
              int Board_Port_Type3_numberIn,
              int NeededService_BoardIn,
              Eng_rule_board_valid_slot Board_Slot_ruleIn) {
              this.ID_Board_Ref = ID_Board_RefIn;
              this.Board_Ref = Board_RefIn;
              this.Board_Ref_Name = Board_Ref_NameIn;
              this.Board_Class = Board_ClassIn;
              this.Board_Slothoused = Board_SlothousedIn;
              this.Board_Port_type1 = Board_Port_type1In;
              this.Board_Port_Type1_number = Board_Port_Type1_numberIn;
              this.Board_Port_type2 = Board_Port_type2In;
              this.Board_Port_Type2_number = Board_Port_Type2_numberIn;
              this.Board_Port_type3 = Board_Port_type3In;
              this.Board_Port_Type3_number = Board_Port_Type3_numberIn;
              this.NeededService_Board = NeededService_BoardIn;
              this.Board_Slot_rule = Board_Slot_ruleIn;
        }
     
     
        /**
         * hasEqualMapping-method will compare two Board_ref instances
         * and return true if they contain same values in all persistent instance
         * variables. If hasEqualMapping returns true, it does not mean the objects
         * are the same instance. However it does mean that in that moment, they
         * are mapped to the same row in database.
         */
        public boolean hasEqualMapping(Board_ref valueObject) {
     
              if (valueObject.getID_Board_Ref() != this.ID_Board_Ref) {
                        return(false);
              }
              if (this.Board_Ref == null) {
                        if (valueObject.getBoard_Ref() != null)
                               return(false);
              } else if (!this.Board_Ref.equals(valueObject.getBoard_Ref())) {
                        return(false);
              }
              if (this.Board_Ref_Name == null) {
                        if (valueObject.getBoard_Ref_Name() != null)
                               return(false);
              } else if (!this.Board_Ref_Name.equals(valueObject.getBoard_Ref_Name())) {
                        return(false);
              }
              if (valueObject.getBoard_Class() != this.Board_Class) {
                        return(false);
              }
              if (valueObject.getBoard_Slothoused() != this.Board_Slothoused) {
                        return(false);
              }
              if (valueObject.getBoard_Port_type1() != this.Board_Port_type1) {
                        return(false);
              }
              if (valueObject.getBoard_Port_Type1_number() != this.Board_Port_Type1_number) {
                        return(false);
              }
              if (valueObject.getBoard_Port_type2() != this.Board_Port_type2) {
                        return(false);
              }
              if (valueObject.getBoard_Port_Type2_number() != this.Board_Port_Type2_number) {
                        return(false);
              }
              if (valueObject.getBoard_Port_type3() != this.Board_Port_type3) {
                        return(false);
              }
              if (valueObject.getBoard_Port_Type3_number() != this.Board_Port_Type3_number) {
                        return(false);
              }
              if (valueObject.getNeededService_Board() != this.NeededService_Board) {
                        return(false);
              }
              if (valueObject.getBoard_Slot_rule() != this.Board_Slot_rule) {
                        return(false);
              }
     
              return true;
        }
     
     
     
        /**
         * toString will return String object representing the state of this
         * valueObject. This is useful during application development, and
         * possibly when application is writing object states in textlog.
         */
        public String toString() {
            StringBuffer out = new StringBuffer(this.getDaogenVersion());
            // StringBuffer out = new StringBuffer();
            out.append("\nclass Board_ref, mapping to table board_ref\n");
            out.append("Persistent attributes: \n");
            out.append("ID_Board_Ref = " + this.ID_Board_Ref + "\n");
            out.append("Board_Ref = " + this.Board_Ref + "\n");
            out.append("Board_Ref_Name = " + this.Board_Ref_Name + "\n");
     
            //out.append("Board_Class = " + this.Board_Class + "\n");
            out.append(this.Board_Class.toString());
            //out.append(Board_Class.toString());
     
            out.append("Board_Slothoused = " + this.Board_Slothoused + "\n");
            //out.append("Board_Port_type1 = " + this.Board_Port_type1.toString() + "\n");
            out.append(this.Board_Port_type1.toString());
            out.append("Board_Port_Type1_number = " + this.Board_Port_Type1_number + "\n");
            //out.append("Board_Port_type2 = " + this.Board_Port_type2 + "\n");
            out.append(this.Board_Port_type2.toString());
            out.append("Board_Port_Type2_number = " + this.Board_Port_Type2_number + "\n");
            //out.append("Board_Port_type3 = " + this.Board_Port_type3 + "\n");
            out.append(this.Board_Port_type3.toString());
            out.append("Board_Port_Type3_number = " + this.Board_Port_Type3_number + "\n");
            out.append("NeededService_Board = " + this.NeededService_Board + "\n");
            //out.append("Board_Slot_rule = " + this.Board_Slot_rule + "\n");
            out.append(this.Board_Slot_rule.toString());
            return out.toString();
     
       // trial avec str
     
    //        String str = "\nclass Board_ref, mapping to table board_ref\n";
    //        str += "Persistent attributes: \n";
    //        str += "ID_Board_Ref = " + this.ID_Board_Ref + "\n";
    //        str += "Board_Ref = " + this.Board_Ref + "\n";
    //        str += "Board_Ref_Name = " + this.Board_Ref_Name + "\n";
    //        str += this.Board_Class.toString();
    //        str += "Board_Slothoused = " + this.Board_Slothoused + "\n";
    //        str += this.Board_Port_type1.toString();
    //        str += "Board_Port_Type1_number = " + this.Board_Port_Type1_number + "\n" ;
    //        str += this.Board_Port_type2.toString();
    //        str += "Board_Port_Type2_number = " + this.Board_Port_Type2_number + "\n";
    //        str += this.Board_Port_type3.toString();
    //        str += "Board_Port_Type3_number = " + this.Board_Port_Type3_number + "\n";
    //        str += "NeededService_Board = " + this.NeededService_Board + "\n";
    //        str += this.Board_Slot_rule.toString();
    //
    //                return str;
     
        }
     
     
        /**
         * Clone will return identical deep copy of this valueObject.
         * Note, that this method is different than the clone() which
         * is defined in java.lang.Object. Here, the retuned cloned object
         * will also have all its attributes cloned.
         */
        public Object clone() {
            Board_ref cloned = new Board_ref();
     
            cloned.setID_Board_Ref(this.ID_Board_Ref);
            if (this.Board_Ref != null)
                 cloned.setBoard_Ref(new String(this.Board_Ref));
            if (this.Board_Ref_Name != null)
                 cloned.setBoard_Ref_Name(new String(this.Board_Ref_Name));
            cloned.setBoard_Class(this.Board_Class);
            cloned.setBoard_Slothoused(this.Board_Slothoused);
            cloned.setBoard_Port_type1(this.Board_Port_type1);
            cloned.setBoard_Port_Type1_number(this.Board_Port_Type1_number);
            cloned.setBoard_Port_type2(this.Board_Port_type2);
            cloned.setBoard_Port_Type2_number(this.Board_Port_Type2_number);
            cloned.setBoard_Port_type3(this.Board_Port_type3);
            cloned.setBoard_Port_Type3_number(this.Board_Port_Type3_number);
            cloned.setNeededService_Board(this.NeededService_Board);
            cloned.setBoard_Slot_rule(this.Board_Slot_rule);
            return cloned;
        }
     
     
     
        /**
         * getDaogenVersion will return information about
         * generator which created these sources.
         */
        public String getDaogenVersion() {
           // return "DaoGen version 2.4.1";
            return "**********************************";
        }
     
    }
    et l'objet DAO :

    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
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
     
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    package port_type_daogen;
     
    import java.sql.*;
    import java.util.*;
    //import java.math.*;
    import java.sql.Connection;
     
     /**
      * Board_ref Data Access Object (DAO).
      * This class contains all database handling that is needed to
      * permanently store and retrieve Board_ref object instances.
      */
     
     
     
     
     
    public class Board_refDao {
     
        // Cache contents:
        private boolean cacheOk;
        private List cacheData;
     
     
        /**
         * Constructor for Dao. This constructor will only reset cache.
         * If extended Dao classes are generated, it is important to
         * make sure resetCache() will be called in constructor.
         */
        public Board_refDao() {
            resetCache();
        }
     
        /**
         * resetCache-method. This is important method when caching is used
         * to keep data in Dao instance. This method must be called whenever
         * the data in table has been changed. This method will mark current
         * cache to be outdated and next time when cacheable data will be
         * retrieved from database, the cache will be rebuilt. Please note
         * that using Dao-cache can have remarkable performace boost or it may
         * not help at all. It all depends on the amount of data and the rate
         * that data is being changed.
         */
        public final void resetCache() {
            cacheOk = false;
            cacheData = null;
        }
     
     
     
        /**
         * createValueObject-method. This method is used when the Dao class needs
         * to create new value object instance. The reason why this method exists
         * is that sometimes the programmer may want to extend also the valueObject
         * and then this method can be overrided to return extended valueObject.
         * NOTE: If you extend the valueObject class, make sure to override the
         * clone() method in it!
         */
        public Board_ref createValueObject() {
              return new Board_ref();
        }
     
     
        /**
         * getObject-method. This will create and load valueObject contents from database
         * using given Primary-Key as identifier. This method is just a convenience method
         * for the real load-method which accepts the valueObject as a parameter. Returned
         * valueObject will be created using the createValueObject() method.
         */
        public Board_ref getObject(Connection conn, int ID_Board_Ref) throws NotFoundException, SQLException {
     
              Board_ref valueObject = createValueObject();
              valueObject.setID_Board_Ref(ID_Board_Ref);
              load(conn, valueObject);
              return valueObject;
        }
     
     
        /**
         * load-method. This will load valueObject contents from database using
         * Primary-Key as identifier. Upper layer should use this so that valueObject
         * instance is created and only primary-key should be specified. Then call
         * this method to complete other persistent information. This method will
         * overwrite all other fields except primary-key and possible runtime variables.
         * If load can not find matching row, NotFoundException will be thrown.
         *
         * @param conn         This method requires working database connection.
         * @param valueObject  This parameter contains the class instance to be loaded.
         *                     Primary-key field must be set for this to work properly.
         */
        public void load(Connection conn, Board_ref valueObject) throws NotFoundException, SQLException {
     
              String sql = "SELECT * FROM board_ref WHERE (ID_Board_Ref = ? ) ";
              PreparedStatement stmt = null;
     
              try {
                   stmt = conn.prepareStatement(sql);
                   stmt.setInt(1, valueObject.getID_Board_Ref());
     
                   singleQuery(conn, stmt, valueObject);
     
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
        /**
         * LoadAll-method. This will read all contents from database table and
         * build a List containing valueObjects. Please note, that this method
         * will consume huge amounts of resources if table has lot's of rows.
         * This should only be used when target tables have only small amounts
         * of data.
         *
         * @param conn         This method requires working database connection.
         */
        public List loadAll(Connection conn) throws SQLException {
     
              // Check the cache status and use Cache if possible.
              if (cacheOk) {
                  return cacheData;
              }
     
              String sql = "SELECT * FROM board_ref ORDER BY ID_Board_Ref ASC ";
              List searchResults = listQuery(conn, conn.prepareStatement(sql));
     
              // Update cache and mark it ready.
              cacheData = searchResults;
              cacheOk = true;
     
              return searchResults;
        }
     
     
     
        /**
         * create-method. This will create new row in database according to supplied
         * valueObject contents. Make sure that values for all NOT NULL columns are
         * correctly specified. Also, if this table does not use automatic surrogate-keys
         * the primary-key must be specified. After INSERT command this method will
         * read the generated primary-key back to valueObject if automatic surrogate-keys
         * were used.
         *
         * @param conn         This method requires working database connection.
         * @param valueObject  This parameter contains the class instance to be created.
         *                     If automatic surrogate-keys are not used the Primary-key
         *                     field must be set for this to work properly.
         */
        public synchronized void create(Connection conn, Board_ref valueObject) throws SQLException {
     
              String sql = "";
              PreparedStatement stmt = null;
              ResultSet result = null;
     
                   // Connection conn   = null;
                   // conn = ConnectDatabaseDAO.getInstance();
    // création des objets DAO
                   //BoardclassDao boardclass_dao = new BoardclassDao ();
              try {
                   sql = "INSERT INTO board_ref ( ID_Board_Ref, Board_Ref, Board_Ref_Name, "
                   + "ID_Board_Class, Board_Slothoused, Board_Port_type1, "
                   + "Board_Port_Type1_number, Board_Port_type2, Board_Port_Type2_number, "
                   + "Board_Port_type3, Board_Port_Type3_number, NeededService_Board, "
                   + "ID_Board_Slot_rule) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
                   stmt = conn.prepareStatement(sql);
     // créer un board class               
              //     if(valueObject.getBoard_Class().getID_BoardClass() == 0){
                       BoardclassDao boardclass_dao = new BoardclassDao ();
                    //DAO<Langage> langageDAO = AbstractDAOFactory .getFactory(FactoryType.DAO_FACTORY)
                    //.getLangageDAO();
                    // obj.setLangage(langageDAO.create(obj.getLangage()));
                //       boardclass_dao.create(conn, valueObject.getBoard_Class());
                      //valueObject.setBoard_Class(boardclass_dao.create(conn, valueObject.getBoard_Class()));
                  //  }
     
                   //BoardclassDao boardclass_dao = new BoardclassDao ();
     
                   stmt.setInt(1, valueObject.getID_Board_Ref());
                   stmt.setString(2, valueObject.getBoard_Ref());
                   stmt.setString(3, valueObject.getBoard_Ref_Name());
                  // stmt.setInt(4, valueObject.getBoard_Class().getID_BoardClass());
                  // valueObject.setBoard_Class(boardclass_dao.create(conn, valueObject.getBoard_Class()));
     
                  // stmt.setBoard_Class(4, boardclass_dao.create(conn, valueObject.getBoard_Class()));
                  // stmt.setBoard_Class (4, valueObject.getBoard_Class());
                   stmt.setInt(4, valueObject.getBoard_Class().getID_BoardClass());
                   stmt.setInt(5, valueObject.getBoard_Slothoused());
                   stmt.setInt(6, valueObject.getBoard_Port_type1().getID_Port_Type());
                   stmt.setInt(7, valueObject.getBoard_Port_Type1_number());
                   stmt.setInt(8, valueObject.getBoard_Port_type2().getID_Port_Type());
                   stmt.setInt(9, valueObject.getBoard_Port_Type2_number());
                   stmt.setInt(10, valueObject.getBoard_Port_type3().getID_Port_Type());
                   stmt.setInt(11, valueObject.getBoard_Port_Type3_number());
                   stmt.setInt(12, valueObject.getNeededService_Board());
                   stmt.setInt(13, valueObject.getBoard_Slot_rule().getEng_Rule_Board_Valid_Slot_ID());
     
                   int rowcount = databaseUpdate(conn, stmt);
                   if (rowcount != 1) {
                        //System.out.println("PrimaryKey Error when updating DB!");
                        throw new SQLException("PrimaryKey Error when updating DB!");
                   }
     
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
     
     
        }
     
     
        /**
         * save-method. This method will save the current state of valueObject to database.
         * Save can not be used to create new instances in database, so upper layer must
         * make sure that the primary-key is correctly specified. Primary-key will indicate
         * which instance is going to be updated in database. If save can not find matching
         * row, NotFoundException will be thrown.
         *
         * @param conn         This method requires working database connection.
         * @param valueObject  This parameter contains the class instance to be saved.
         *                     Primary-key field must be set for this to work properly.
         */
        public void save(Connection conn, Board_ref valueObject)
              throws NotFoundException, SQLException {
     
              String sql = "UPDATE board_ref SET Board_Ref = ?, Board_Ref_Name = ?, ID_Board_Class = ?, "
                   + "Board_Slothoused = ?, Board_Port_type1 = ?, Board_Port_Type1_number = ?, "
                   + "Board_Port_type2 = ?, Board_Port_Type2_number = ?, Board_Port_type3 = ?, "
                   + "Board_Port_Type3_number = ?, NeededService_Board = ?, ID_Board_Slot_rule = ? WHERE (ID_Board_Ref = ? ) ";
              PreparedStatement stmt = null;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  stmt.setString(1, valueObject.getBoard_Ref());
                  stmt.setString(2, valueObject.getBoard_Ref_Name());
                  stmt.setInt(3, valueObject.getBoard_Class().getID_BoardClass());
                  stmt.setInt(4, valueObject.getBoard_Slothoused());
                  stmt.setInt(5, valueObject.getBoard_Port_type1().getID_Port_Type());
                  stmt.setInt(6, valueObject.getBoard_Port_Type1_number());
                  stmt.setInt(7, valueObject.getBoard_Port_type2().getID_Port_Type());
                  stmt.setInt(8, valueObject.getBoard_Port_Type2_number());
                  stmt.setInt(9, valueObject.getBoard_Port_type3().getID_Port_Type());
                  stmt.setInt(10, valueObject.getBoard_Port_Type3_number());
                  stmt.setInt(11, valueObject.getNeededService_Board());
                  stmt.setInt(12, valueObject.getBoard_Slot_rule().getEng_Rule_Board_Valid_Slot_ID());
     
                  stmt.setInt(13, valueObject.getID_Board_Ref());
     
                  int rowcount = databaseUpdate(conn, stmt);
                  if (rowcount == 0) {
                       //System.out.println("Object could not be saved! (PrimaryKey not found)");
                       throw new NotFoundException("Object could not be saved! (PrimaryKey not found)");
                  }
                  if (rowcount > 1) {
                       //System.out.println("PrimaryKey Error when updating DB! (Many objects were affected!)");
                       throw new SQLException("PrimaryKey Error when updating DB! (Many objects were affected!)");
                  }
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
        /**
         * delete-method. This method will remove the information from database as identified by
         * by primary-key in supplied valueObject. Once valueObject has been deleted it can not
         * be restored by calling save. Restoring can only be done using create method but if
         * database is using automatic surrogate-keys, the resulting object will have different
         * primary-key than what it was in the deleted object. If delete can not find matching row,
         * NotFoundException will be thrown.
         *
         * @param conn         This method requires working database connection.
         * @param valueObject  This parameter contains the class instance to be deleted.
         *                     Primary-key field must be set for this to work properly.
         */
        public void delete(Connection conn, Board_ref valueObject)
              throws NotFoundException, SQLException {
     
              String sql = "DELETE FROM board_ref WHERE (ID_Board_Ref = ? ) ";
              PreparedStatement stmt = null;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  stmt.setInt(1, valueObject.getID_Board_Ref());
     
                  int rowcount = databaseUpdate(conn, stmt);
                  if (rowcount == 0) {
                       //System.out.println("Object could not be deleted (PrimaryKey not found)");
                       throw new NotFoundException("Object could not be deleted! (PrimaryKey not found)");
                  }
                  if (rowcount > 1) {
                       //System.out.println("PrimaryKey Error when updating DB! (Many objects were deleted!)");
                       throw new SQLException("PrimaryKey Error when updating DB! (Many objects were deleted!)");
                  }
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
        /**
         * deleteAll-method. This method will remove all information from the table that matches
         * this Dao and ValueObject couple. This should be the most efficient way to clear table.
         * Once deleteAll has been called, no valueObject that has been created before can be
         * restored by calling save. Restoring can only be done using create method but if database
         * is using automatic surrogate-keys, the resulting object will have different primary-key
         * than what it was in the deleted object. (Note, the implementation of this method should
         * be different with different DB backends.)
         *
         * @param conn         This method requires working database connection.
         */
        public void deleteAll(Connection conn) throws SQLException {
     
              String sql = "DELETE FROM board_ref";
              PreparedStatement stmt = null;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  int rowcount = databaseUpdate(conn, stmt);
              } finally {
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
        /**
         * coutAll-method. This method will return the number of all rows from table that matches
         * this Dao. The implementation will simply execute "select count(primarykey) from table".
         * If table is empty, the return value is 0. This method should be used before calling
         * loadAll, to make sure table has not too many rows.
         *
         * @param conn         This method requires working database connection.
         */
        public int countAll(Connection conn) throws SQLException {
     
              // Check the cache status and use Cache if possible.
              if (cacheOk) {
                  return cacheData.size();
              }
     
     
              String sql = "SELECT count(*) FROM board_ref";
              PreparedStatement stmt = null;
              ResultSet result = null;
              int allRows = 0;
     
              try {
                  stmt = conn.prepareStatement(sql);
                  result = stmt.executeQuery();
     
                  if (result.next())
                      allRows = result.getInt(1);
              } finally {
                  if (result != null)
                      result.close();
                  if (stmt != null)
                      stmt.close();
              }
              return allRows;
        }
     
     
        /**
         * searchMatching-Method. This method provides searching capability to
         * get matching valueObjects from database. It works by searching all
         * objects that match permanent instance variables of given object.
         * Upper layer should use this by setting some parameters in valueObject
         * and then  call searchMatching. The result will be 0-N objects in a List,
         * all matching those criteria you specified. Those instance-variables that
         * have NULL values are excluded in search-criteria.
         *
         * @param conn         This method requires working database connection.
         * @param valueObject  This parameter contains the class instance where search will be based.
         *                     Primary-key field should not be set.
         */
        public List searchMatching(Connection conn, Board_ref valueObject) throws SQLException {
     
              List searchResults;
     
              boolean first = true;
              StringBuffer sql = new StringBuffer("SELECT * FROM board_ref WHERE 1=1 ");
     
              if (valueObject.getID_Board_Ref() != 0) {
                  if (first) { first = false; }
                  sql.append("AND ID_Board_Ref = ").append(valueObject.getID_Board_Ref()).append(" ");
              }
     
              if (valueObject.getBoard_Ref() != null) {
                  if (first) { first = false; }
                  sql.append("AND Board_Ref LIKE '").append(valueObject.getBoard_Ref()).append("%' ");
              }
     
              if (valueObject.getBoard_Ref_Name() != null) {
                  if (first) { first = false; }
                  sql.append("AND Board_Ref_Name LIKE '").append(valueObject.getBoard_Ref_Name()).append("%' ");
              }
     
              if (valueObject.getBoard_Class().getID_BoardClass() != 0) {
                  if (first) { first = false; }
                  sql.append("AND ID_Board_Class = ").append(valueObject.getBoard_Class().getID_BoardClass()).append(" ");
              }
     
              if (valueObject.getBoard_Slothoused() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Board_Slothoused = ").append(valueObject.getBoard_Slothoused()).append(" ");
              }
     
              if (valueObject.getBoard_Port_type1().getID_Port_Type() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Board_Port_type1 = ").append(valueObject.getBoard_Port_type1().getID_Port_Type()).append(" ");
              }
     
              if (valueObject.getBoard_Port_Type1_number() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Board_Port_Type1_number = ").append(valueObject.getBoard_Port_Type1_number()).append(" ");
              }
     
              if (valueObject.getBoard_Port_type2().getID_Port_Type() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Board_Port_type2 = ").append(valueObject.getBoard_Port_type2().getID_Port_Type()).append(" ");
              }
     
              if (valueObject.getBoard_Port_Type2_number() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Board_Port_Type2_number = ").append(valueObject.getBoard_Port_Type2_number()).append(" ");
              }
     
              if (valueObject.getBoard_Port_type3().getID_Port_Type() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Board_Port_type3 = ").append(valueObject.getBoard_Port_type3().getID_Port_Type()).append(" ");
              }
     
              if (valueObject.getBoard_Port_Type3_number() != 0) {
                  if (first) { first = false; }
                  sql.append("AND Board_Port_Type3_number = ").append(valueObject.getBoard_Port_Type3_number()).append(" ");
              }
     
              if (valueObject.getNeededService_Board() != 0) {
                  if (first) { first = false; }
                  sql.append("AND NeededService_Board = ").append(valueObject.getNeededService_Board()).append(" ");
              }
     
              if (valueObject.getBoard_Slot_rule().getEng_Rule_Board_Valid_Slot_ID() != 0) {
                  if (first) { first = false; }
                  sql.append("AND ID_Board_Slot_rule = ").append(valueObject.getBoard_Slot_rule().getEng_Rule_Board_Valid_Slot_ID()).append(" ");
              }
     
     
              sql.append("ORDER BY ID_Board_Ref ASC ");
     
              // Prevent accidential full table results.
              // Use loadAll if all rows must be returned.
              if (first)
                   searchResults = new ArrayList();
              else
                   searchResults = listQuery(conn, conn.prepareStatement(sql.toString()));
     
              return searchResults;
        }
     
     
        /**
         * getDaogenVersion will return information about
         * generator which created these sources.
         */
        public String getDaogenVersion() {
            return "DaoGen version 2.4.1";
        }
     
     
        /**
         * databaseUpdate-method. This method is a helper method for internal use. It will execute
         * all database handling that will change the information in tables. SELECT queries will
         * not be executed here however. The return value indicates how many rows were affected.
         * This method will also make sure that if cache is used, it will reset when data changes.
         *
         * @param conn         This method requires working database connection.
         * @param stmt         This parameter contains the SQL statement to be excuted.
         */
        protected int databaseUpdate(Connection conn, PreparedStatement stmt) throws SQLException {
     
              int result = stmt.executeUpdate();
     
              resetCache();
     
              return result;
        }
     
     
     
        /**
         * databaseQuery-method. This method is a helper method for internal use. It will execute
         * all database queries that will return only one row. The resultset will be converted
         * to valueObject. If no rows were found, NotFoundException will be thrown.
         *
         * @param conn         This method requires working database connection.
         * @param stmt         This parameter contains the SQL statement to be excuted.
         * @param valueObject  Class-instance where resulting data will be stored.
         */
        protected void singleQuery(Connection conn, PreparedStatement stmt, Board_ref valueObject)
              throws NotFoundException, SQLException {
     
              ResultSet result = null;
     
              try {
                  result = stmt.executeQuery();
         // à ajouter *************************************************************
              BoardclassDao board_class_dao = new BoardclassDao();
              Port_typeDao port_type_dao = new Port_typeDao () ;
              Port_typeDao port_type_dao2 = new Port_typeDao () ;
              Port_typeDao port_type_dao3 = new Port_typeDao () ;
              Eng_rule_board_valid_slotDao eng_rule_board_valid_slot_dao = new Eng_rule_board_valid_slotDao();
     
              Boardclass bc = new Boardclass () ;
              Port_type pt1 = new Port_type () ;
              Port_type pt2 = new Port_type () ;
              Port_type pt3 = new Port_type () ;
              Eng_rule_board_valid_slot valid_slot = new Eng_rule_board_valid_slot();
        // fin de l'ajout *********************************************
     
           //  br =  board_class_dao.getObject(conn, result.getInt("ID_Board_Class"));
                  if (result.next()) {
        // à ajouter ******************************************************************************************
                       bc =  board_class_dao.getObject(conn, result.getInt("ID_Board_Class"));
                       pt1 =  port_type_dao.getObject(conn, result.getInt("Board_Port_type1"));
                       pt2 =  port_type_dao2.getObject(conn, result.getInt("Board_Port_type2"));
                       pt3 =  port_type_dao3.getObject(conn, result.getInt("Board_Port_type3"));
                       valid_slot = eng_rule_board_valid_slot_dao.getObject(conn, result.getInt("ID_Board_Slot_rule"));
        // fin de l'ajout *************************************************************************************
     
                       valueObject.setID_Board_Ref(result.getInt("ID_Board_Ref"));
                       valueObject.setBoard_Ref(result.getString("Board_Ref"));
                       valueObject.setBoard_Ref_Name(result.getString("Board_Ref_Name"));
                    //   valueObject.getBoard_Class().setID_BoardClass((result.getInt("ID_Board_Class")));
                       valueObject.getBoard_Class().setID_BoardClass(bc.getID_BoardClass());
       // un point à suivre******************************************************************************
     
              // ceci permet d'avoir 2 comme valeur pour boardclass_name
                       //valueObject.getBoard_Class().setBoardClass_Name(result.getString("ID_Board_Class"));
              // ceci permet d'avoir null comme valeur pour boardclass
                      //valueObject.getBoard_Class().setBoardClass_Name(result.getInt("ID_Board_Class"));
              // ceci ne fonctionne pas
                       //valueObject.getBoard_Class().setBoardClass_Name((getBoard_Class(result.getInt("ID_Board_Class")).getBoardClass_Name()));
     //***********************************************************************************************
     
                       // ceci permet de mettre la valeur de setBoardClass_Name
                       valueObject.getBoard_Class().setBoardClass_Name(bc.getBoardClass_Name());
     
                       valueObject.setBoard_Slothoused(result.getInt("Board_Slothoused"));
              // avec set all
                     //  valueObject.getBoard_Class().setAll(bc.getID_BoardClass(), bc.getBoardClass_Name());
     
                     //     valueObject.getBoard_Port_type1().setID_Port_Type((result.getInt("Board_Port_type1")));
         // à ajouter *****************************************************
                       valueObject.getBoard_Port_type1().setID_Port_Type(pt1.getID_Port_Type());
                       valueObject.getBoard_Port_type1().setPort_Type_Name(pt1.getPort_Type_Name());
                       valueObject.getBoard_Port_type1().setPort_Type_capacity(pt1.getPort_Type_capacity());
         // fin de l'ajout ************************************************
                       valueObject.setBoard_Port_Type1_number(result.getInt("Board_Port_Type1_number"));
                      // valueObject.getBoard_Port_type2().setID_Port_Type((result.getInt("Board_Port_type2")));
     
                       valueObject.getBoard_Port_type2().setID_Port_Type(pt2.getID_Port_Type());
                       valueObject.getBoard_Port_type2().setPort_Type_Name(pt2.getPort_Type_Name());
                       valueObject.getBoard_Port_type2().setPort_Type_capacity(pt2.getPort_Type_capacity());
     
                       valueObject.setBoard_Port_Type2_number(result.getInt("Board_Port_Type2_number"));
     
                       //valueObject.getBoard_Port_type3().setID_Port_Type((result.getInt("Board_Port_type3")));
     
                       valueObject.getBoard_Port_type3().setID_Port_Type(pt3.getID_Port_Type());
                       valueObject.getBoard_Port_type3().setPort_Type_Name(pt3.getPort_Type_Name());
                       valueObject.getBoard_Port_type3().setPort_Type_capacity(pt3.getPort_Type_capacity());
     
                       valueObject.setBoard_Port_Type3_number(result.getInt("Board_Port_Type3_number"));
                       valueObject.setNeededService_Board(result.getInt("NeededService_Board"));
     
                       //valueObject.getBoard_Slot_rule().setEng_Rule_Board_Valid_Slot_ID((result.getInt("ID_Board_Slot_rule")));
     
                       valueObject.getBoard_Slot_rule().setEng_Rule_Board_Valid_Slot_ID(valid_slot.getEng_Rule_Board_Valid_Slot_ID());
                       valueObject.getBoard_Slot_rule().setBoard_Ref(valid_slot.getBoard_Ref());
                       valueObject.getBoard_Slot_rule().setBoard_valid_slot_numbers(valid_slot.getBoard_valid_slot_numbers());
                       valueObject.getBoard_Slot_rule().setID_NeType(valid_slot.getID_NeType());
                       valueObject.getBoard_Slot_rule().setSlot_count(valid_slot.getSlot_count());
     
     
                  } else {
                        //System.out.println("Board_ref Object Not Found!");
                        throw new NotFoundException("Board_ref Object Not Found!");
                  }
              } finally {
                  if (result != null)
                      result.close();
                  if (stmt != null)
                      stmt.close();
              }
        }
     
     
        /**
         * databaseQuery-method. This method is a helper method for internal use. It will execute
         * all database queries that will return multiple rows. The resultset will be converted
         * to the List of valueObjects. If no rows were found, an empty List will be returned.
         *
         * @param conn         This method requires working database connection.
         * @param stmt         This parameter contains the SQL statement to be excuted.
         */
        protected List listQuery(Connection conn, PreparedStatement stmt) throws SQLException {
     
              ArrayList searchResults = new ArrayList();
              ResultSet result = null;
     
              try {
                  result = stmt.executeQuery();
     
                  while (result.next()) {
                       Board_ref temp = createValueObject();
     
                       temp.setID_Board_Ref(result.getInt("ID_Board_Ref"));
                       temp.setBoard_Ref(result.getString("Board_Ref"));
                       temp.setBoard_Ref_Name(result.getString("Board_Ref_Name"));
                       temp.getBoard_Class().setID_BoardClass((result.getInt("ID_Board_Class")));
                       temp.setBoard_Slothoused(result.getInt("Board_Slothoused"));
                       temp.getBoard_Port_type1().setID_Port_Type((result.getInt("Board_Port_type1")));
                       temp.setBoard_Port_Type1_number(result.getInt("Board_Port_Type1_number"));
                       temp.getBoard_Port_type2().setID_Port_Type((result.getInt("Board_Port_type2")));
                       temp.setBoard_Port_Type2_number(result.getInt("Board_Port_Type2_number"));
                       temp.getBoard_Port_type3().setID_Port_Type((result.getInt("Board_Port_type3")));
                       temp.setBoard_Port_Type3_number(result.getInt("Board_Port_Type3_number"));
                       temp.setNeededService_Board(result.getInt("NeededService_Board"));
                       temp.getBoard_Slot_rule().setEng_Rule_Board_Valid_Slot_ID((result.getInt("ID_Board_Slot_rule")));
     
                       searchResults.add(temp);
                  }
     
              } finally {
                  if (result != null)
                      result.close();
                  if (stmt != null)
                      stmt.close();
              }
     
              return (List)searchResults;
        }
     
     
    }
    3) une table qui contient un foriegn key vers la clé primaire de la meme table. je ne suis toujours pas arrivé à résoudre ce probème!!

    voici un site générateur automatique de classes objet et classes DAO :
    http://titaniclinux.net/daogen .

    Merci.

  16. #16
    Rédacteur/Modérateur
    Avatar de Logan Mauzaize
    Homme Profil pro
    Architecte technique
    Inscrit en
    Août 2005
    Messages
    2 894
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Architecte technique
    Secteur : Transports

    Informations forums :
    Inscription : Août 2005
    Messages : 2 894
    Points : 7 083
    Points
    7 083
    Par défaut
    1. Il faut que les différents DAO puissent partager la même transaction et donc la même connexion.
    2. Il faut contrairement à ton cas que les méthodes public des DAO ne gèrent pas de connexion.
    3. Il faut que les DAO puissent déprendre des uns et des autres. Par exemple ton Board_refDao ne vérifie pas la persistance des Port_type référencés.
    4. Il faut utiliser des requêtes paramétrées plutôt que construire une chaîne à la volée (attention au hack ou erreurs)


    Pour ton problème pur, je vois rien de compliquer :
    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
     
    class FooBar {
      int id = -1;
      FooBar parent = null;
    }
     
    class FooBarDao extends AbstractDao {
      public void save(FooBar foobar) {
        Connection conn = pushConnection(); // Open connection if requires
        try {
          String sql;
          if (foobar.id >=0) {
            sql = "UPDATE foobar SET parent_id=? WHERE id=?"
          }
          else {
            foobar.id = nextId();
            sql = "INSERT INTO foobar(parent_id,id) VALUES (?,?)"
          }
          PreparedStatement stmt = conn.createPreparedStatement(sql);
          try {
            if (foobar.parent != null) {
              stmt.setInt(1, foobar.parent.id); // Assume parent is persisted
            }
            else {
              stmt.setNull(1, Types.NUMERIC);
            }
            stmt.setInt(2, foobar.id);
            stmt.executeUpdate();
          }
          finally {
            stmt.close();
          }
          pushCommit(); // Mark connection as commitable before closing.
        }
        catch (SQLException e) {
           rollback(); // Prevent connection comitting
           throw new DaoException("Unable to save foobar", e);
        }
        catch (RuntimeException e) {
          rollback(); // Prevent connection comitting
          throw e;
        }
        catch (Error e) {
          rollback(); // Prevent connection comitting
          throw e;
        }
        finally {
          popConnection(); // Close connection if requires
        }
      }
    }
    Java : Cours et tutoriels - FAQ - Java SE 8 API - Programmation concurrente
    Ceylon : Installation - Concepts de base - Typage - Appels et arguments

    ECM = Exemple(reproduit le problème) Complet (code compilable) Minimal (ne postez pas votre application !)
    Une solution vous convient ? N'oubliez pas le tag
    Signature par pitipoisson

  17. #17
    Futur Membre du Club
    Profil pro
    Inscrit en
    Décembre 2007
    Messages
    5
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2007
    Messages : 5
    Points : 6
    Points
    6
    Par défaut Comment faire des jointures avec ce principe DAO ?
    Bonjour,

    j'expérimente ce tuto pour mon apprentissage et je me pose la question suivante:
    Comment faire une requête qui utilise plusieurs tables en utilisant les principes du tuto présenté?

    Faut-il y un super objet qui autorise à faire une requête sur 2 tables?

    De ce que j'ai compris c'est que chaque DAO représente une table en base et que une table DAO manipule uniquement les données de sa table.
    D'où ma question, comment faire une jointure si un objet DAO ne peut faire de requête que sur sa propre table en base?

    En vous remerciant,

  18. #18
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    453
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 453
    Points : 883
    Points
    883
    Billets dans le blog
    5
    Par défaut
    Bonjour,

    Je suis en désaccord avec un point dans ce tutoriel.

    Dans ce tutoriel, la DAO est une classe abstraite. Or, ça devrait être une interface. Les personnes (ou plus exactement les classes dans lesquelles on va injecter la bonne DAO) ne doivent voir que les méthodes, et ne pas avoir vent de l'implémentation.

    Je rappelle, pour la même raison, que Joshua Bloch explique qu'il faut préférer les interfaces aux classes abstraites.

    Par ailleurs, la connexion à la BDD est publique, soit visible par l'extérieur (comme un contrôleur qui ne doit pas connaitre la BDD).

    Pire, on spécifie directement la BDD. Si on veut changer...

    La connexion devrait être injecté.

    Cordialement

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

    Informations forums :
    Inscription : Novembre 2006
    Messages : 7 310
    Points : 9 522
    Points
    9 522
    Billets dans le blog
    1
    Par défaut
    C'est une ancienne discussion, les ORM n'étaient pas omniprésents à l'époque.

    Ceci dit, par rapport au dernier commentaire, classe abstraite ou interface, dans bien des cas, surtout avec les ORM, la classe abstraite est bien plus adaptée puisqu'elle contient un code générique, la seule chose qui doit être spécifiée dans la classe c'est le type cible. Ce qui n'exclue pas d'avoir une interface en plus pour la raison qui suit.
    Une interface aurait été plus adaptée si on avait eu plusieurs classes abstraites en fonction de spécificités, d'ailleurs tel qu'est codé la classe abstraite de l'exemple, comme elle inclue la connexion, ça aurait été utile... surtout que l'exemple parle de DAO XML... étendant DAO... laquelle contient une Connection... Bof bof bof...

    Pour la connexion, je suis d'accord, elle n'a pas à être créée dans la classe abstraite.

    Par contre,si vraiment on veut critiquer quelque chose, il y a un truc qui m'écorche les yeux c'est la méthode update
    Utiliser un Statement au lieu d'un PreparedStatement est juste une grossière erreur. Essayez de mettre un nom comme "O'Reilly" dans la base... plantage assuré

    Sinon, ça montre quand même bien les principes de la DAO, donc ne soyons pas trop pointilleux
    N'oubliez pas de consulter les FAQ Java et les cours et tutoriels Java

  20. #20
    Membre éclairé

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    453
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 453
    Points : 883
    Points
    883
    Billets dans le blog
    5
    Par défaut
    Bonnjour,

    Une classe abstraite, c'est pour faire du Template Method ( https://en.wikipedia.org/wiki/Template_method_pattern )

    L'interface, c'est le contrat. C'est ce que voit le client et ce qui est injecté dans divers classe (via Spring, ou les EJB ou constructeur) ou donné par factory au pire.

    Celui qui utilise la DAO, il a juste besoin d'une interface DAO, et d'utiliser les méthodes de cette interface. Il n'a pas besoin de savoir comment ça fonctionne.

    C'est d'ailleurs un principe pour faire du bon code ( https://fr.wikipedia.org/wiki/Masqua...%27information ).

    Cordialement.

Discussions similaires

  1. meilleure base de données avec java
    Par mial dans le forum JDBC
    Réponses: 11
    Dernier message: 10/11/2010, 11h49
  2. Réponses: 1
    Dernier message: 27/05/2009, 21h02
  3. [Article] Mapper sa base de données avec le pattern DAO
    Par cysboy dans le forum Architecture
    Réponses: 1
    Dernier message: 27/05/2009, 21h02
  4. Modifier le nom d'une base de donnée avec erreur sy
    Par mmn dans le forum MS SQL Server
    Réponses: 2
    Dernier message: 25/11/2003, 10h12

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