Package org.springframework.jdbc.support

Examples of org.springframework.jdbc.support.GeneratedKeyHolder


  private UpdateResult updateInternal(String procName, String sql, Object... args) throws DataAccessException {
    sql = checkAuthPlaceholder(sql);
    return new CallTemplate<UpdateResult>() {
      @Override
      UpdateResult doCall(String sql, MapSqlParameterSource params) {
        KeyHolder kh = new GeneratedKeyHolder();
        int rowsAffected = getJdbcTemplate().update(sql, params, kh);
        return new UpdateResult(kh, rowsAffected);
      }
    }.call(procName, sql, args);
  }
View Full Code Here


  ///// insert with start
  /**
   * 适用sqlserver,mysql 自动生成主键
   */
  protected void insertWithGeneratedKey(Object entity, String insertSql) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    getNamedParameterJdbcTemplate().update(insertSql, new BeanPropertySqlParameterSource(entity) , keyHolder);
    setIdentifierProperty(entity, keyHolder.getKey().longValue());
  }
View Full Code Here

    return this.namedParameterJdbcTemplate.update(sql, param);
  }
  public Object executeSqlReturnKey(final String sql, Map<String, Object> param) {
    Object keyValue = null;
    try{
      KeyHolder keyHolder = new GeneratedKeyHolder();
      SqlParameterSource sqlp  = new MapSqlParameterSource(param);
      this.namedParameterJdbcTemplate.update(sql,sqlp, keyHolder);
      keyValue = keyHolder.getKey().longValue();
    }catch (Exception e) {
      keyValue = null;
    }
    return keyValue;
  }
View Full Code Here

    if (debug) {
      logger.info("sql:" + sql);
      logger.info("object:" + object);
    }
    SqlParameterSource namedParam = new BeanPropertySqlParameterSource(object);
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int ret = getNameParameterJdbcTemplate().update(sql, namedParam, keyHolder);
    if (ret <= 0)
      return ret;
    try {
      if (keyHolder.getKey() == null)
        return ret;
      ret = keyHolder.getKey().intValue();
      return ret;
    } catch (Exception e) {
      return ret;
    }
  }
View Full Code Here

      throws DataAccessException {
   
    return new CallTemplate<UpdateResult>() {
      @Override
      UpdateResult doCall(String sql, MapSqlParameterSource params) {
        KeyHolder kh = new GeneratedKeyHolder();
        int rowsAffected = getJdbcTemplate().update(sql,
            params, kh);
        return new UpdateResult(kh, rowsAffected);
      }
    }.call(sql_, args_)
View Full Code Here

      jdbcTemplate.update(UPDATE_VENUE, venueData.getName(), venueData.getPostalAddress(), venueData.getLatitude(), venueData.getLongitude(), venueData.getLocationHint(), 1, venueId);
      logger.info("Updated venue (ID = " + venueId + ")");
      return eventId;
    } catch (IncorrectResultSizeDataAccessException e) {
      // insert if it doesn't exist
      KeyHolder keyHolder = new GeneratedKeyHolder();
      jdbcTemplate.update(new PreparedStatementCreatorFactory(INSERT_EVENT, new int[] {VARCHAR, VARCHAR, VARCHAR, TIMESTAMP, TIMESTAMP, VARCHAR, BIGINT})
          .newPreparedStatementCreator(new Object[] {eventData.getName(), eventData.getDescription(), eventData.getTimeZone(), eventData.getFirstDay(), eventData.getLastDay(), eventData.getAbbreviation(), eventData.getMemberGroupId()}), keyHolder);
      Number eventId = keyHolder.getKey();
      logger.info("Created event (ID = " + eventId + ")");
      jdbcTemplate.update(new PreparedStatementCreatorFactory(INSERT_VENUE, new int[] {VARCHAR, VARCHAR, DOUBLE, DOUBLE, VARCHAR, BIGINT})
          .newPreparedStatementCreator(new Object[] {venueData.getName(), venueData.getPostalAddress(), venueData.getLatitude(), venueData.getLongitude(), venueData.getLocationHint(), 1}), keyHolder);
      Number venueId = keyHolder.getKey();
      logger.info("Created vanue (ID = " + venueId + ")");
      jdbcTemplate.update(INSERT_EVENT_VENUE, eventId, venueId);
      jdbcTemplate.update(INSERT_EXTERNAL_EVENT, eventId, eventData.getSourceId(), eventData.getSource(), new Date());
      return eventId.longValue();
    }
View Full Code Here

      jdbcTemplate.update(UPDATE_LEADER, leaderData.getName(), leaderData.getBio(), leaderData.getPersonalUrl(), leaderData.getTwitterId(), leaderId);
      logger.info("Updated leader (ID = " + leaderId + ")");
      return leaderId;
    } catch (IncorrectResultSizeDataAccessException e) {
      // insert if it doesn't exist
      KeyHolder keyHolder = new GeneratedKeyHolder();
      jdbcTemplate.update(new PreparedStatementCreatorFactory(INSERT_LEADER, new int[] {VARCHAR, VARCHAR, VARCHAR, VARCHAR})
          .newPreparedStatementCreator(new Object[] {leaderData.getName(), leaderData.getBio(), leaderData.getPersonalUrl(), leaderData.getTwitterId()}), keyHolder);
      long leaderId = keyHolder.getKey().longValue();
      jdbcTemplate.update(INSERT_EXTERNAL_LEADER, leaderId, leaderData.getSourceId(), leaderData.getSource(), new Date());
      logger.info("Created leader (ID = " + leaderId + ")");
      return leaderId;
    }
  };
View Full Code Here

      jdbcTemplate.update(UPDATE_TIMESLOT, timeSlotData.getEventId(), timeSlotData.getLabel(), timeSlotData.getStartTime(), timeSlotData.getEndTime(), timeSlotId);
      logger.info("Updated timeslot (ID = " + timeSlotId + ")");
      return timeSlotId;
    } catch (IncorrectResultSizeDataAccessException e) {
      // insert if it doesn't exist
      KeyHolder keyHolder = new GeneratedKeyHolder();
      jdbcTemplate.update(new PreparedStatementCreatorFactory(INSERT_TIMESLOT, new int[] {BIGINT, VARCHAR, TIMESTAMP, TIMESTAMP})
        .newPreparedStatementCreator(new Object[] {timeSlotData.getEventId(), timeSlotData.getLabel(), timeSlotData.getStartTime(), timeSlotData.getEndTime()}), keyHolder);
      long timeSlotId = keyHolder.getKey().longValue();
      jdbcTemplate.update(INSERT_EXTERNAL_TIMESLOT, timeSlotId, timeSlotData.getSourceId(), timeSlotData.getSource(), new Date());
      logger.info("Created timeslot (ID = " + timeSlotId + ")");
      return timeSlotId;     
    }
  }
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()) {
      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

TOP

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

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.