Package org.springframework.jdbc.support

Examples of org.springframework.jdbc.support.KeyHolder


            sql.append(")");
        }
        logger.debug("SQL for Save: " + sql);
        int updateCount = 0;
        if (isNewRow && persistentObject.isUsingGeneratedKeysStrategy()) {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            final String prepSql = sql.toString();
            updateCount = getJdbcTemplate().update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                    PreparedStatement ps = con.prepareStatement(prepSql, Statement.RETURN_GENERATED_KEYS);
                    int cnt = 0;
View Full Code Here


   *         getKey()一个数字主键<br>
   *         getKeys()复合主键Map结构<br>
   *         getKeyList()多个主键由多个Map组成的List
   */
  public KeyHolder updateNamedParamer(String hql, SqlParameterSource sps) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.getSimpleJdbcTemplate().getNamedParameterJdbcOperations().update(
        hql, sps, keyHolder);
    return keyHolder;
  }
View Full Code Here

  /**
   * Method to execute the insert generating single key
   */
  private Number executeInsertAndReturnKeyInternal(final List<Object> values) {
    KeyHolder kh = executeInsertAndReturnKeyHolderInternal(values);
    if (kh != null && kh.getKey() != null) {
      return kh.getKey();
    }
    else {
      throw new DataIntegrityViolationException("Unable to retreive the generated key for the insert: " +
          getInsertString());
    }
View Full Code Here

   */
  private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<Object> values) {
    if (logger.isDebugEnabled()) {
      logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values);
    }
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    if (!this.tableMetaDataContext.isGetGeneratedKeysSupported()) {
      if (!this.tableMetaDataContext.isGetGeneratedKeysSimulated()) {
        throw new InvalidDataAccessResourceUsageException(
            "The getGeneratedKeys feature is not supported by this database");
      }
      if (getGeneratedKeyNames().length < 1) {
        throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specificed. " +
            "Using the generated keys features requires specifying the name(s) of the generated column(s)");
      }
      if (getGeneratedKeyNames().length > 1) {
        throw new InvalidDataAccessApiUsageException(
            "Current database only supports retreiving the key for a single column. There are " +
            getGeneratedKeyNames().length  + " columns specified: " + Arrays.asList(getGeneratedKeyNames()));
      }
      // This is a hack to be able to get the generated key from a database that doesn't support
      // get generated keys feature.  HSQL is one, PostgreSQL is another.  Has to be done with the same
      // connection.
      jdbcTemplate.execute(new ConnectionCallback() {
        public Object doInConnection(Connection con) throws SQLException, DataAccessException {
          // Do the insert
          PreparedStatement ps = null;
          try {
            ps = con.prepareStatement(getInsertString());
            setParameterValues(ps, values, null);
            ps.executeUpdate();
          } finally {
            JdbcUtils.closeStatement(ps);
          }
          //Get the key
          String keyQuery = tableMetaDataContext.getSimulationQueryForGetGeneratedKey(
              tableMetaDataContext.getTableName(),
              getGeneratedKeyNames()[0]);
          Statement keyStmt = null;
          ResultSet rs = null;
          HashMap keys = new HashMap(1);
          try {
            keyStmt = con.createStatement();
            rs = keyStmt.executeQuery(keyQuery);
            if (rs.next()) {
              long key = rs.getLong(1);
              keys.put(getGeneratedKeyNames()[0], key);
              keyHolder.getKeyList().add(keys);
            }
          } finally {
            JdbcUtils.closeResultSet(rs);
            JdbcUtils.closeStatement(keyStmt);
          }
View Full Code Here

  /**
   * Method to execute the insert generating single key
   */
  private Number executeInsertAndReturnKeyInternal(final List<Object> values) {
    KeyHolder kh = executeInsertAndReturnKeyHolderInternal(values);
    if (kh != null && kh.getKey() != null) {
      return kh.getKey();
    }
    else {
      throw new DataIntegrityViolationException("Unable to retrieve the generated key for the insert: " +
          getInsertString());
    }
View Full Code Here

   */
  private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<Object> values) {
    if (logger.isDebugEnabled()) {
      logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values);
    }
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    if (this.tableMetaDataContext.isGetGeneratedKeysSupported()) {
      jdbcTemplate.update(
          new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
              PreparedStatement ps = prepareStatementForGeneratedKeys(con);
              setParameterValues(ps, values, getInsertTypes());
              return ps;
            }
          },
          keyHolder);
    }
    else {
      if (!this.tableMetaDataContext.isGetGeneratedKeysSimulated()) {
        throw new InvalidDataAccessResourceUsageException(
            "The getGeneratedKeys feature is not supported by this database");
      }
      if (getGeneratedKeyNames().length < 1) {
        throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specificed. " +
            "Using the generated keys features requires specifying the name(s) of the generated column(s)");
      }
      if (getGeneratedKeyNames().length > 1) {
        throw new InvalidDataAccessApiUsageException(
            "Current database only supports retreiving the key for a single column. There are " +
            getGeneratedKeyNames().length  + " columns specified: " + Arrays.asList(getGeneratedKeyNames()));
      }
      // This is a hack to be able to get the generated key from a database that doesn't support
      // get generated keys feature.  HSQL is one, PostgreSQL is another.  Postgres uses a RETURNING
      // clause while HSQL uses a second query that has to be executed with the same connection.
      final String keyQuery = tableMetaDataContext.getSimulationQueryForGetGeneratedKey(
          tableMetaDataContext.getTableName(),
          getGeneratedKeyNames()[0]);
      Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null");
      if (keyQuery.toUpperCase().startsWith("RETURNING")) {
        Long key = jdbcTemplate.queryForLong(
            getInsertString() + " " + keyQuery,
            values.toArray(new Object[values.size()]));
        HashMap keys = new HashMap(1);
        keys.put(getGeneratedKeyNames()[0], key);
        keyHolder.getKeyList().add(keys);
      }
      else {
        jdbcTemplate.execute(new ConnectionCallback() {
          public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            // Do the insert
            PreparedStatement ps = null;
            try {
              ps = con.prepareStatement(getInsertString());
              setParameterValues(ps, values, getInsertTypes());
              ps.executeUpdate();
            } finally {
              JdbcUtils.closeStatement(ps);
            }
            //Get the key
            Statement keyStmt = null;
            ResultSet rs = null;
            HashMap keys = new HashMap(1);
            try {
              keyStmt = con.createStatement();
              rs = keyStmt.executeQuery(keyQuery);
              if (rs.next()) {
                long key = rs.getLong(1);
                keys.put(getGeneratedKeyNames()[0], key);
                keyHolder.getKeyList().add(keys);
              }
            } finally {
              JdbcUtils.closeResultSet(rs);
              JdbcUtils.closeStatement(keyStmt);
            }
View Full Code Here

         }
     return resultSet.size();
   }

   public int executeInsert(IMockController controller, IQuery query) {
      KeyHolder holder = new GeneratedKeyHolder();
      int types[] = new int[query.getParametersLength()];
      int i = 0;
      for ( IQueryParameter p : query ){
         types[i++] = StatementCreatorUtils.javaTypeToSqlParameterType(p.getColumnMetadata().getType());
      }
      int res = getWriteJdbcTemplate().update(
               new PreparedStatementCreatorFactory(query.getSql(),types)
               .newPreparedStatementCreator(query.getParameterValues()), holder);
      if ( holder != null && holder.getKeyList().size() == 1 ){
         for ( ColumnMetadata col : controller.getColumns().values() ){
            if ( col.isIdentity() == Boolean.TRUE ){
               Number number = holder.getKey();
               if ( Long.class.isAssignableFrom(col.getType()) ){
                  controller.setValue(col.getSetterMethod(), (Long)number);
               }
               //TODO handle other types
               break;
View Full Code Here

  /**
   * Method to execute the insert generating single key
   */
  private Number executeInsertAndReturnKeyInternal(final List<Object> values) {
    KeyHolder kh = executeInsertAndReturnKeyHolderInternal(values);
    if (kh != null && kh.getKey() != null) {
      return kh.getKey();
    }
    else {
      throw new DataIntegrityViolationException("Unable to retreive the generated key for the insert: " +
          getInsertString());
    }
View Full Code Here

   */
  private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<Object> values) {
    if (logger.isDebugEnabled()) {
      logger.debug("The following parameters are used for call " + getInsertString() + " with: " + values);
    }
    final KeyHolder keyHolder = new GeneratedKeyHolder();
    if (this.tableMetaDataContext.isGetGeneratedKeysSupported()) {
      jdbcTemplate.update(
          new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
              PreparedStatement ps = prepareStatementForGeneratedKeys(con);
              setParameterValues(ps, values, null);
              return ps;
            }
          },
          keyHolder);
    }
    else {
      if (!this.tableMetaDataContext.isGetGeneratedKeysSimulated()) {
        throw new InvalidDataAccessResourceUsageException(
            "The getGeneratedKeys feature is not supported by this database");
      }
      if (getGeneratedKeyNames().length < 1) {
        throw new InvalidDataAccessApiUsageException("Generated Key Name(s) not specificed. " +
            "Using the generated keys features requires specifying the name(s) of the generated column(s)");
      }
      if (getGeneratedKeyNames().length > 1) {
        throw new InvalidDataAccessApiUsageException(
            "Current database only supports retreiving the key for a single column. There are " +
            getGeneratedKeyNames().length  + " columns specified: " + Arrays.asList(getGeneratedKeyNames()));
      }
      // This is a hack to be able to get the generated key from a database that doesn't support
      // get generated keys feature.  HSQL is one, PostgreSQL is another.  Postgres uses a RETURNING
      // clause while HSQL uses a second query that has to be executed with the same connection.
      final String keyQuery = tableMetaDataContext.getSimulationQueryForGetGeneratedKey(
          tableMetaDataContext.getTableName(),
          getGeneratedKeyNames()[0]);
      Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null");
      if (keyQuery.toUpperCase().startsWith("RETURNING")) {
        Long key = jdbcTemplate.queryForLong(
            getInsertString() + " " + keyQuery,
            values.toArray(new Object[values.size()]));
        HashMap keys = new HashMap(1);
        keys.put(getGeneratedKeyNames()[0], key);
        keyHolder.getKeyList().add(keys);
      }
      else {
        jdbcTemplate.execute(new ConnectionCallback() {
          public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            // Do the insert
            PreparedStatement ps = null;
            try {
              ps = con.prepareStatement(getInsertString());
              setParameterValues(ps, values, null);
              ps.executeUpdate();
            } finally {
              JdbcUtils.closeStatement(ps);
            }
            //Get the key
            Statement keyStmt = null;
            ResultSet rs = null;
            HashMap keys = new HashMap(1);
            try {
              keyStmt = con.createStatement();
              rs = keyStmt.executeQuery(keyQuery);
              if (rs.next()) {
                long key = rs.getLong(1);
                keys.put(getGeneratedKeyNames()[0], key);
                keyHolder.getKeyList().add(keys);
              }
            } finally {
              JdbcUtils.closeResultSet(rs);
              JdbcUtils.closeStatement(keyStmt);
            }
View Full Code Here

    replay();
    ctrlResultSet.replay();
    ctrlResultSetMetaData.replay();

    GeneratedKeysUpdater pc = new GeneratedKeysUpdater();
    KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
    int rowsAffected = pc.run("rod", generatedKeyHolder);
    assertEquals(1, rowsAffected);
    assertEquals(1, generatedKeyHolder.getKeyList().size());
    assertEquals(11, generatedKeyHolder.getKey().intValue());
  }
View Full Code Here

TOP

Related Classes of org.springframework.jdbc.support.KeyHolder

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.