use of org.springframework.jdbc.support.GeneratedKeyHolder in project spring-framework by spring-projects.
the class AbstractJdbcInsert method executeInsertAndReturnKeyHolderInternal.
/**
* Delegate method to execute the insert, generating any number of keys.
*/
private KeyHolder executeInsertAndReturnKeyHolderInternal(final List<?> 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<>(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<>(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);
}
return null;
}
});
}
return keyHolder;
}
return keyHolder;
}
use of org.springframework.jdbc.support.GeneratedKeyHolder in project dal by ctripcorp.
the class DaoOfProject method insertProject.
public int insertProject(final Project project) {
KeyHolder holder = new GeneratedKeyHolder();
this.jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("INSERT INTO project ( name, namespace, dal_group_id,dal_config_name,update_user_no,update_time) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS);
ps.setString(1, project.getName());
ps.setString(2, project.getNamespace());
ps.setInt(3, project.getDal_group_id());
ps.setString(4, project.getDal_config_name());
ps.setString(5, project.getUpdate_user_no());
ps.setTimestamp(6, project.getUpdate_time());
return ps;
}
}, holder);
return holder.getKey().intValue();
}
use of org.springframework.jdbc.support.GeneratedKeyHolder in project disconf by knightliao.
the class GenericDao method createAndFetchKey.
/**
* @param entity
* @param sql
* @param params
*/
@SuppressWarnings("unchecked")
private ENTITY createAndFetchKey(ENTITY entity, final String sql, final List<Object> params) {
KeyHolder keyHolder = new GeneratedKeyHolder();
recordLog(sql);
// 执行操作
int rowCount = this.jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql);
int index = 1;
for (Object param : params) {
ps.setObject(index++, param);
}
return ps;
}
}, keyHolder);
// 如果插入成功则获取keyHolder中的key
if (rowCount != 0 && keyHolder.getKey() != null) {
Class<KEY> keyClass = orMapping.getKeyClass();
if (keyClass.equals(Integer.class)) {
entity.setId((KEY) Integer.valueOf(keyHolder.getKey().intValue()));
} else if (keyClass.equals(Long.class)) {
entity.setId((KEY) Long.valueOf(keyHolder.getKey().longValue()));
}
}
return rowCount == 1 ? entity : null;
}
use of org.springframework.jdbc.support.GeneratedKeyHolder in project disconf by knightliao.
the class GenericDao method createAndFetchUpdateRow.
// FIXME
@SuppressWarnings("unchecked")
private int createAndFetchUpdateRow(ENTITY entity, final String sql, final List<Object> params) {
KeyHolder keyHolder = new GeneratedKeyHolder();
recordLog(sql);
// 执行操作
int rowCount = this.jdbcTemplate.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql);
int index = 1;
for (Object param : params) {
ps.setObject(index++, param);
}
return ps;
}
}, keyHolder);
// 如果插入成功则获取keyHolder中的key
if (rowCount != 0) {
Class<KEY> keyClass = orMapping.getKeyClass();
if (keyClass.equals(Integer.class)) {
entity.setId((KEY) Integer.valueOf(keyHolder.getKey().intValue()));
} else if (keyClass.equals(Long.class)) {
entity.setId((KEY) Long.valueOf(keyHolder.getKey().longValue()));
}
}
return rowCount;
}
use of org.springframework.jdbc.support.GeneratedKeyHolder in project spring-framework by spring-projects.
the class SqlUpdateTests method testUpdateAndGeneratedKeys.
@Test
public void testUpdateAndGeneratedKeys() throws SQLException {
given(resultSetMetaData.getColumnCount()).willReturn(1);
given(resultSetMetaData.getColumnLabel(1)).willReturn("1");
given(resultSet.getMetaData()).willReturn(resultSetMetaData);
given(resultSet.next()).willReturn(true, false);
given(resultSet.getObject(1)).willReturn(11);
given(preparedStatement.executeUpdate()).willReturn(1);
given(preparedStatement.getGeneratedKeys()).willReturn(resultSet);
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();
}
Aggregations