Java Code Examples for org.springframework.jdbc.core.PreparedStatementCreatorFactory#setReturnGeneratedKeys()

The following examples show how to use org.springframework.jdbc.core.PreparedStatementCreatorFactory#setReturnGeneratedKeys() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JdbcDemonstratingRepository.java    From Spring-Boot-2-Fundamentals with MIT License 6 votes vote down vote up
/**
 * Demonstrate how to insert and retrieve a generated key.
 * <p>
 * The {@code id} column of the {@code short_message} table can generated ids.
 * In order to retrieve the newly generated id, we need an update that returns
 * some data (a JDBC 3 feature). Spring supports this with a keyholder.
 * <p>
 * Unfortunately, {@link JdbcTemplate#update(PreparedStatementCreator, KeyHolder)}
 * needs a {@link PreparedStatementCreator} which is a bit overwhelming
 * here.
 */
public void insertMessage(Author author, String text) {
    String sql = "INSERT INTO short_message(author_id, posted_time, message_text)" +
            " VALUES(?, ?, ?)";
    Timestamp currentTimestamp = Timestamp.valueOf(LocalDateTime.now());

    PreparedStatementCreatorFactory statementCreatorFactory =
            new PreparedStatementCreatorFactory(sql,
                    Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR);
    statementCreatorFactory.setReturnGeneratedKeys(true);
    statementCreatorFactory.setGeneratedKeysColumnNames("id");
    PreparedStatementCreator preparedStatementCreator =
            statementCreatorFactory.newPreparedStatementCreator(
                    new Object[]{author.getId(), currentTimestamp, text});

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int update = jdbcTemplate.update(preparedStatementCreator, keyHolder);
    log.info("auto-insert created {} row with key {}", update, keyHolder.getKey());
}
 
Example 2
Source File: JdbcDemonstratingRepository.java    From Spring-Boot-2-Fundamentals with MIT License 6 votes vote down vote up
/**
 * Demonstrate how to insert and retrieve a generated key.
 * <p>
 * The {@code id} column of the {@code short_message} table can generated ids.
 * In order to retrieve the newly generated id, we need an update that returns
 * some data (a JDBC 3 feature). Spring supports this with a keyholder.
 * <p>
 * Unfortunately, {@link JdbcTemplate#update(PreparedStatementCreator, KeyHolder)}
 * needs a {@link PreparedStatementCreator} which is a bit overwhelming
 * here.
 */
public void insertMessage(Author author, String text) {
    String sql = "INSERT INTO short_message(author_id, posted_time, message_text)" +
            " VALUES(?, ?, ?)";
    Timestamp currentTimestamp = Timestamp.valueOf(LocalDateTime.now());

    PreparedStatementCreatorFactory statementCreatorFactory =
            new PreparedStatementCreatorFactory(sql,
                    Types.INTEGER, Types.TIMESTAMP, Types.VARCHAR);
    statementCreatorFactory.setReturnGeneratedKeys(true);
    statementCreatorFactory.setGeneratedKeysColumnNames("id");
    PreparedStatementCreator preparedStatementCreator =
            statementCreatorFactory.newPreparedStatementCreator(
                    new Object[]{author.getId(), currentTimestamp, text});

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int update = jdbcTemplate.update(preparedStatementCreator, keyHolder);
    log.info("auto-insert created {} row with key {}", update, keyHolder.getKey());
}
 
Example 3
Source File: NamedParameterJdbcTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public int update(
		String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
		throws DataAccessException {

	ParsedSql parsedSql = getParsedSql(sql);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null);
	List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
	PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters);
	if (keyColumnNames != null) {
		pscf.setGeneratedKeysColumnNames(keyColumnNames);
	}
	else {
		pscf.setReturnGeneratedKeys(true);
	}
	return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder);
}
 
Example 4
Source File: NamedParameterJdbcTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public int update(
		String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
		throws DataAccessException {

	ParsedSql parsedSql = getParsedSql(sql);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null);
	List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
	PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters);
	if (keyColumnNames != null) {
		pscf.setGeneratedKeysColumnNames(keyColumnNames);
	}
	else {
		pscf.setReturnGeneratedKeys(true);
	}
	return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder);
}
 
Example 5
Source File: NamedParameterJdbcTemplate.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Override
public int update(
		String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder, String[] keyColumnNames)
		throws DataAccessException {

	ParsedSql parsedSql = getParsedSql(sql);
	String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
	Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null);
	List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
	PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters);
	if (keyColumnNames != null) {
		pscf.setGeneratedKeysColumnNames(keyColumnNames);
	}
	else {
		pscf.setReturnGeneratedKeys(true);
	}
	return getJdbcOperations().update(pscf.newPreparedStatementCreator(params), generatedKeyHolder);
}
 
Example 6
Source File: TransactionImpl.java    From gemini with Apache License 2.0 5 votes vote down vote up
private PreparedStatement getPreparedStatement(String sql, @Nullable Map<String, ?> parameters, boolean returnKeys) throws SQLException {
    SqlParameterSource paramSource = new MapSqlParameterSource(parameters);
    ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql);
    String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource);
    List<SqlParameter> declaredParameters = NamedParameterUtils.buildSqlParameterList(parsedSql, paramSource);
    Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null);
    PreparedStatementCreatorFactory psCreatorFactory = new PreparedStatementCreatorFactory(sqlToUse, declaredParameters);
    psCreatorFactory.setReturnGeneratedKeys(returnKeys);
    PreparedStatementCreator psCreator = psCreatorFactory.newPreparedStatementCreator(params);
    PreparedStatement preparedStatement = psCreator.createPreparedStatement(connection);
    logger.debug(preparedStatement.unwrap(PreparedStatement.class).toString());
    return preparedStatement;
}
 
Example 7
Source File: JdbcSpittleRepository.java    From Project with Apache License 2.0 5 votes vote down vote up
public Spittle save(Spittle spittle) {
  
  System.out.println("--> " + spittle.getMessage());
  
  
  String sql = "insert into Spittle (message, created_at, latitude, longitude)" +
      " values (?, ?, ?, ?)";
  PreparedStatementCreatorFactory statementCreatorFactory = new PreparedStatementCreatorFactory(sql, Types.VARCHAR, Types.TIMESTAMP, Types.DOUBLE, Types.DOUBLE);
  statementCreatorFactory.setReturnGeneratedKeys(true);
  PreparedStatementCreator creator = statementCreatorFactory.newPreparedStatementCreator(new Object[] {
      spittle.getMessage(),
      spittle.getTime(),
      spittle.getLatitude(),
      spittle.getLongitude()
  });

  
  GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
  jdbc.update(creator, keyHolder);
  return new Spittle(
      keyHolder.getKey().longValue(), 
      spittle.getMessage(), 
      spittle.getTime(), 
      spittle.getLongitude(), 
      spittle.getLatitude());
  
  
}
 
Example 8
Source File: DefaultMessageStore.java    From qmq with Apache License 2.0 5 votes vote down vote up
private PreparedStatementCreatorFactory createFactory() {
    List<SqlParameter> parameters = new ArrayList<>();
    parameters.add(new SqlParameter("content", Types.LONGVARCHAR));
    parameters.add(new SqlParameter("create_time", Types.TIMESTAMP));
    PreparedStatementCreatorFactory factory = new PreparedStatementCreatorFactory(sqlStatementProvider.getInsertSql(), parameters);
    factory.setReturnGeneratedKeys(true);
    return factory;
}
 
Example 9
Source File: BaseRepository.java    From fish-admin with MIT License 5 votes vote down vote up
public long insert(List<String> columns, List<Object> args, int[] types) {
    String insertColumns = primaryKeyName();
    String insertPlaceholders = "nextval('"+tableName()+"_id_seq')";
    for (String column : columns) {
        insertColumns += "," + column;
        insertPlaceholders += ",?";
    }

    insertColumns += ", " + createdAtName();
    insertPlaceholders += ", now()";
    insertColumns += ", " + updatedAtName();
    insertPlaceholders += ", now()";

    String sql = "insert into " + tableName() +
            " ("+insertColumns+") values ("+insertPlaceholders+")";

    KeyHolder keyHolder = new GeneratedKeyHolder();

    PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory(sql, types);
    pscf.setReturnGeneratedKeys(true);
    try {
        logger.info("insert.sql: {}, args: {}", sql, jsonMapper.writeValueAsString(args));
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    writeJdbcTemplate.update(pscf.newPreparedStatementCreator(args), keyHolder);
    if (keyHolder.getKeyList() != null && !keyHolder.getKeyList().isEmpty()) {
        return (long) keyHolder.getKeyList().get(0).get(primaryKeyName());
    }
    return -1;
}