Package org.springframework.jdbc.support

Examples of org.springframework.jdbc.support.KeyHolder


   */
  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()) {
      getJdbcTemplate().update(
          new PreparedStatementCreator() {
            @Override
            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 specified. " +
            "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 retrieving 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 = this.tableMetaDataContext.getSimulationQueryForGetGeneratedKey(
          this.tableMetaDataContext.getTableName(), getGeneratedKeyNames()[0]);
      Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null");
      if (keyQuery.toUpperCase().startsWith("RETURNING")) {
        Long key = getJdbcTemplate().queryForObject(getInsertString() + " " + keyQuery,
            values.toArray(new Object[values.size()]), Long.class);
        Map<String, Object> keys = new HashMap<String, Object>(1);
        keys.put(getGeneratedKeyNames()[0], key);
        keyHolder.getKeyList().add(keys);
      }
      else {
        getJdbcTemplate().execute(new ConnectionCallback<Object>() {
          @Override
          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;
            Map<String, Object> keys = new HashMap<String, Object>(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


    given(connection.prepareStatement(INSERT_GENERATE_KEYS,
        PreparedStatement.RETURN_GENERATED_KEYS)
      ).willReturn(preparedStatement);

    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());
    verify(preparedStatement).setString(1, "rod");
    verify(resultSet).close();
  }
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

  /**
   * 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

    JdbcTemplate insert = new JdbcTemplate(dataSource);

    final Class<T> type = this.type;
    final String createStatement = Dao.createStatements.get(type);

    KeyHolder holder = new GeneratedKeyHolder();
    try {
      // Create a prepared statement.
      insert.update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(
            Connection connection) throws SQLException {

          String createStatementToUse = null;

          // Use the cached value if we have one, otherwise, generate
          // one and cache it.
          if (createStatement != null) {
            createStatementToUse = createStatement;
          } else {
            createStatementToUse = strat.generateCreateStatement(t);

            Dao.createStatements.put(type, createStatementToUse);
          }

          PreparedStatement ps = connection.prepareStatement(
              createStatementToUse,
              Statement.RETURN_GENERATED_KEYS);

          strat.prepareStatement(ps, t);

          return ps;
        }

      }, holder);
    } catch (Exception e) {
      e.printStackTrace();
    }

    int id = holder.getKey().intValue();

    // Get the T that we just inserted.
    return this.select(id);
  }
View Full Code Here

  }

  public Integer create(Resource newResource) {
    int columnType = newResource.getIdIndex().getColumnInfo().getColumnType();
    Object[] parameters = new Object[] { newResource.getName(), newResource.getPartitionDimension().getId(), JdbcTypeMapper.jdbcTypeToString(columnType),newResource.isPartitioningResource()};
    KeyHolder generatedKey = new GeneratedKeyHolder();
    JdbcTemplate j = getJdbcTemplate();
    PreparedStatementCreatorFactory creatorFactory = new PreparedStatementCreatorFactory(
        "INSERT INTO resource_metadata (name,dimension_id,db_type,is_partitioning_resource) VALUES (?,?,?,?)",
        new int[] {Types.VARCHAR,Types.INTEGER,Types.VARCHAR,Types.BIT});
    creatorFactory.setReturnGeneratedKeys(true);
    int rows = j.update(creatorFactory
        .newPreparedStatementCreator(parameters), generatedKey);
    if (rows != 1)
      throw new HiveRuntimeException("Unable to create Resource: "
          + parameters);
    if (generatedKey.getKeyList().size() == 0)
      throw new HiveRuntimeException("Unable to retrieve generated primary key");
    newResource.updateId(generatedKey.getKey().intValue());
   
    // dependencies
    for (SecondaryIndex si : newResource.getSecondaryIndexes())
      new SecondaryIndexDao(ds).create(si);
     
View Full Code Here

  }

  public void update(Resource resource) {
    int columnType = resource.getIdIndex().getColumnInfo().getColumnType();
    Object[] parameters = new Object[] { resource.getName(), resource.getPartitionDimension().getId(), JdbcTypeMapper.jdbcTypeToString(columnType),resource.isPartitioningResource(),resource.getId()};
    KeyHolder generatedKey = new GeneratedKeyHolder();
    JdbcTemplate j = getJdbcTemplate();
    PreparedStatementCreatorFactory creatorFactory = new PreparedStatementCreatorFactory(
        "UPDATE resource_metadata SET name=?,dimension_id=?,db_type=?,is_partitioning_resource=? WHERE id=?",
        new int[] {Types.VARCHAR,Types.INTEGER,Types.VARCHAR,Types.INTEGER,Types.BIT});
    creatorFactory.setReturnGeneratedKeys(true);
View Full Code Here

          newObject.getResource().getId(),
          newObject.getColumnInfo().getName(),
          JdbcTypeMapper.jdbcTypeToString(newObject.getColumnInfo()
              .getColumnType()) };
   
    KeyHolder generatedKey = new GeneratedKeyHolder();
    JdbcTemplate j = getJdbcTemplate();
    PreparedStatementCreatorFactory creatorFactory = new PreparedStatementCreatorFactory(
        "INSERT INTO secondary_index_metadata (resource_id,column_name,db_type) VALUES (?,?,?)",
        new int[] { Types.INTEGER, Types.VARCHAR, Types.VARCHAR });
    creatorFactory.setReturnGeneratedKeys(true);
    int rows = j.update(creatorFactory
        .newPreparedStatementCreator(parameters), generatedKey);
    if (rows != 1)
      throw new HiveRuntimeException("Unable to create secondary index: "
          + parameters);
    if (generatedKey.getKeyList().size() == 0)
      throw new HiveRuntimeException("Unable to retrieve generated primary key");
    newObject.updateId(generatedKey.getKey().intValue());
 
    return new Integer(newObject.getId());
  }
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.