No cache version.

Caching disabled. Default setting for this page:enabled (code LNG204)
If the display is too slow, you can disable the user mode to view the cached version.

Vous devez être membre et vous identifier pour publier un article.
Les visiteurs peuvent toutefois commenter chaque article par une réponse.

[Derby] Récupérer la valeur d’un auto incrément

Astuces de l’Infobrol (Java)Article publié le 20/10/2008 14:37:00


Avec Derby (JavaDB, la base de données Java depuis 1.6) comme avec d’autres bases de données, nous pouvons utiliser une valeur auto-incrémentée, générée par la DB, pour identifier chaque ligne d’une table (je n’insisterais jamais assez sur l’importance d’avoir des identifiants totalement indépendants de la logique des données).

Voici un exemple de tables, une table personne, qui contient les informations minimales, et une table enseignant, qui pourrait comporter des informations plus spécifiques (comme par exemple, son école, la matière enseignée, etc.).
Chaque enseignant est au minimum une personne, donc nous pouvons lier la table enseignant à l’identifiant de la personne.

Les tables


  1. CREATE TABLE person (
  2. id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
  3. lastName VARCHAR(50),
  4. firstName VARCHAR(50),
  5. birthdate DATE,
  6. sex VARCHAR(50)
  7. );
  8.  
  9. CREATE TABLE teacher (
  10. personId INTEGER NOT NULL
  11. /* + autre champs spécifiques à l’enseignant */
  12. );


Derby et le code Java


Mais si nous utilisons JDBC et pas hibernate, comment récupérer l’identifiant de la personne qui vient d’être sauvée?

  1. private void insertTeacher(Teacher teacher) {
  2. try {
  3. // Statement.RETURN_GENERATED_KEYS to use the generated id to insert
  4. // into the teacher table
  5. PreparedStatement psInsert = DerbyFactory
  6. .getDBConnection()
  7. .prepareStatement(
  8. "INSERT INTO person (lastName, firstName, birthdate, sex) VALUES (?,?,?,?)",
  9. Statement.RETURN_GENERATED_KEYS);
  10.  
  11. psInsert.setString(1, teacher.getLastName());
  12. psInsert.setString(2, teacher.getFirstName());
  13. psInsert.setDate(3, new java.sql.Date(teacher.getBirthdate()
  14. .getTime()));
  15. psInsert.setString(4, teacher.getSex().name());
  16. ConsoleHelper.writeTitle("Insert into db\n" + psInsert.toString());
  17. psInsert.executeUpdate();
  18.  
  19. // Reads the generated id
  20. ResultSet rs = psInsert.getGeneratedKeys();
  21.  
  22. while (rs.next()) {
  23. int lastIndex = rs.getInt(1);
  24. psInsert = DerbyFactory.getDBConnection().prepareStatement(
  25. "INSERT INTO teacher(personId) VALUES ( ? )");
  26. psInsert.setInt(1, lastIndex);
  27. ConsoleHelper.writeTitle("Insert into db\n"
  28. + psInsert.toString());
  29. psInsert.executeUpdate();
  30. }
  31. } catch (Exception ex) {
  32. ex.printStackTrace();
  33. }
  34. }


Nous devons déclarer, au moment de préparer la requête d’insertion de la personne, que nous désirons utiliser la valeur générée par Derby.

  1. Statement.RETURN_GENERATED_KEYS


ensuite nous pouvons lire cette valeur après avoir exécuté la requête
  1. ResultSet rs = psInsert.getGeneratedKeys();
  2. //suite du code...
  3. int lastIndex = rs.getInt(1);


Avatar :: Steph Un article de Steph

Source : indéterminée


Sélection, tri et recherche d'articles
FILTRER :
TRIER :1er critère : 2e critère :
CHERCHER : Dans les titres Dans le contenu


[Afficher les liens en fonction des critères du formulaire ci-dessus]

English translation

You have asked to visit this site in English. For now, only the interface is translated, but not all the content yet.

If you want to help me in translations, your contribution is welcome. All you need to do is register on the site, and send me a message asking me to add you to the group of translators, which will give you the opportunity to translate the pages you want. A link at the bottom of each translated page indicates that you are the translator, and has a link to your profile.

Thank you in advance.

Document created the 13/09/2004, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/ast-rf-445.html

The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.