0 Replies Latest reply on Aug 15, 2001 5:06 AM by Karsten Jegstad

    javax.ejb.DuplicateKeyException: Entity with key 1 already e

    Karsten Jegstad Newbie

      My Entety EJB makes an Exception when i try to insert a row in a table at the MS SQLSERVER.MS SQLSERVER creates the unike PK, which i retrieve, after the INSERT(?,?) of the other 2 values..

      anyone know why ?

      code:
      --------------------------------------------
      public Integer ejbCreate (String name, String active) throws CreateException {
      Connection connection = null;
      PreparedStatement stmt = null;
      ResultSet rset = null;
      int pk = -1;
      String query = "INSERT INTO UNIT(name,active) VALUES (?,?)";
      try {
      //STEP1 : open the connection
      connection = this.getConnection();
      stmt = connection.prepareStatement(query);
      stmt.setString(1, name);
      stmt.setString(2, active);
      //STEP 2: Obtain the desired resultset with a query
      stmt.executeUpdate();
      query = "SELECT @@IDENTITY";
      stmt = connection.prepareStatement(query);
      rset = stmt.executeQuery();
      //GET THE PK-VALUE
      rset.next();
      pk = rset.getInt(1);
      } //try
      catch (SQLException e) {
      e.printStackTrace();
      throw new CreateException(e.getMessage());
      } //catch
      catch (NamingException e) {
      e.printStackTrace();
      throw new CreateException(e.getMessage());
      } //catch
      finally {
      // Cleanup that needs to occur whether we leave via a return or exception
      try {
      if (stmt != null) {
      stmt.close();
      stmt = null;
      } //if
      if (connection != null) {
      connection.close();
      connection = null;
      } //if

      } //try
      catch (Exception e) {
      e.printStackTrace();
      } //catch
      //INSERTING THE PK-VALUE IN THE ENTITY EJB
      this.setUnitnr(new Integer(pk));
      return new Integer(pk);
      } //finally
      } // ejbCreate