本文整理汇总了Java中org.springframework.jdbc.support.GeneratedKeyHolder类的典型用法代码示例。如果您正苦于以下问题:Java GeneratedKeyHolder类的具体用法?Java GeneratedKeyHolder怎么用?Java GeneratedKeyHolder使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
GeneratedKeyHolder类属于org.springframework.jdbc.support包,在下文中一共展示了GeneratedKeyHolder类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: add
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Override
public Object add(Object object) {
SqlModel<Object> sqlModel = sqlBuilder.insertSelectiveSql(object);
checkSqlModel(sqlModel);
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(object);
KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
namedPjdbcTemplate.update(sqlModel.getSql(), paramSource, generatedKeyHolder);
Number num = generatedKeyHolder.getKey();
String[] primaryKeys = sqlModel.getPrimaryKeys();
if(primaryKeys != null && primaryKeys.length > 0){
BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
beanWrapper.setPropertyValue(primaryKeys[0], num);
}
return object;
}
示例2: testInsert
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Test
public void testInsert() {
GeneratedAlwaysRecord record = new GeneratedAlwaysRecord();
record.setId(100);
record.setFirstName("Bob");
record.setLastName("Jones");
InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record)
.into(generatedAlways)
.map(id).toProperty("id")
.map(firstName).toProperty("firstName")
.map(lastName).toProperty("lastName")
.build()
.render(RenderingStrategy.SPRING_NAMED_PARAMETER);
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord());
KeyHolder keyHolder = new GeneratedKeyHolder();
int rows = template.update(insertStatement.getInsertStatement(), parameterSource, keyHolder);
String generatedKey = (String) keyHolder.getKeys().get("FULL_NAME");
assertThat(rows).isEqualTo(1);
assertThat(generatedKey).isEqualTo("Bob Jones");
}
示例3: insertUser
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Override
public Long insertUser(User u) {
StringBuffer sql = new StringBuffer("");
sql.append(" insert into user ");
sql.append(" ( username, password ) ");
sql.append(" values ( ");
sql.append(" :username ");
sql.append(" , :password ");
sql.append(" ) ");
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(u);
KeyHolder generatedKeyHolder = new GeneratedKeyHolder();
int rows = getDao().update(sql.toString(), paramSource, generatedKeyHolder);
if(rows > 0 ){
Long userId = generatedKeyHolder.getKey().longValue();
u.setId(userId);
}
return u.getId();
}
示例4: saveOrderRecord
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
private Integer saveOrderRecord(JdbcTemplate jdbcTemplate, final int userId, final long money) {
final String INSERT_SQL = "INSERT INTO `order` (`order_id`, `user_id`, `money`, `create_time`) VALUES (NULL, ?, ?, ?);";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"id"});
ps.setInt(1, userId);
ps.setLong(2, money);
ps.setDate(3, new Date(System.currentTimeMillis()));
return ps;
}
},
keyHolder);
return keyHolder.getKey().intValue();
}
示例5: insertWithAutoGeneratedKey
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
private <S extends T> S insertWithAutoGeneratedKey(S entity, Map<String, Object> columns) {
removeIdColumns(columns);
final String insertQuery = sqlGenerator.insert(table, columns);
final Object[] queryParams = columns.values().toArray();
final GeneratedKeyHolder key = new GeneratedKeyHolder();
jdbcOps.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
String idColumnName = table.getPkColumns().get(0);
PreparedStatement ps = con.prepareStatement(insertQuery, new String[]{idColumnName});
for (int i = 0; i < queryParams.length; ++i) {
ps.setObject(i + 1, queryParams[i]);
}
return ps;
}
}, key);
return postInsert(entity, key.getKey());
}
示例6: insertSelective
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
public void insertSelective(Object record){
try {
Entity entity=getEntity(record.getClass());
final Set<Entity.Column> insertColumn = getNotNullColumn(record, entity);
final StringBuilder sql = new StringBuilder();
sql.append(SqlHelper.insertIntoTable(entity.getTableName()));
sql.append(SqlHelper.insertColumns(record, insertColumn));
System.out.println(sql.toString());
KeyHolder holder=new GeneratedKeyHolder();
jdbcTemplate.update(sql.toString(), getParameterMap(record, insertColumn,false), holder, new String[]{entity.getPrimaryKey().getName()});
int primaryKeyValue = holder.getKey().intValue();
entity.getPrimaryKey().getField().set(record, primaryKeyValue);
} catch (Exception e) {
e.printStackTrace();
}
}
示例7: create
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Transactional
public User create(String tenantSchema, final User user) {
final String sql = MessageFormat.format(TENANT_SQL_TEMPLATE, tenantSchema, "insert into user(name,password) values(?,?)");
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
return ps;
}
}, holder);
int newUserId = holder.getKey().intValue();
user.setId(newUserId);
return user;
}
示例8: getCurrentGithubId
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
public long getCurrentGithubId() {
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "SELECT stat_id FROM github_stats WHERE stat_date = current_date()";
long statId = -1;
try {
statId = jdbcTemplate.queryForObject(sql, Long.class);
} catch (EmptyResultDataAccessException e) {
jdbcTemplate.update(
new PreparedStatementCreator() {
String INSERT_SQL = "INSERT INTO github_stats (stat_date) VALUES (current_date())";
public PreparedStatement createPreparedStatement(Connection cn) throws SQLException {
PreparedStatement ps = cn.prepareStatement(INSERT_SQL, new String[] {"stat_id"});
return ps;
}
},
keyHolder);
statId = keyHolder.getKey().longValue();
}
logger.info("Current GitHub Stats ID: " + statId);
return statId;
}
示例9: githubStatRecordKeyReturned
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Test
public void githubStatRecordKeyReturned() throws Exception {
KeyHolder keyHolder = new GeneratedKeyHolder();
long statId = -1L;
try {
statId = jdbcTemplate.queryForObject("SELECT stat_id FROM github_stats WHERE stat_date = '2010-10-10'", Long.class);
} catch (EmptyResultDataAccessException e) {
jdbcTemplate.update(
new PreparedStatementCreator() {
String INSERT_SQL = "INSERT INTO github_stats (stat_date) VALUES ('2010-10-10')";
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(INSERT_SQL, new String[]{"stat_id"});
return ps;
}
},
keyHolder);
statId = keyHolder.getKey().longValue();
}
assertThat(statId).isGreaterThan(0);
}
示例10: insert
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
public Idea insert(Idea idea, User currentUser) {
String sql = "insert into idea (title, description, user_id) values (?,?,?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, new String[] { "id" });
ps.setString(1, idea.getTitle());
ps.setString(2, idea.getDescription());
ps.setLong(3, currentUser.getId());
return ps;
}
}, keyHolder);
idea.setId(keyHolder.getKey().longValue());
return idea;
}
示例11: saveGraph
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Override
@Transactional(readOnly=false)
public long saveGraph(String graphName) {
Object[] args = new Object[1];
args[0] = graphName;
Map<String, Object> params = new HashMap<String, Object>();
params.put("name", graphName);
MapSqlParameterSource sqlParameterSource = new MapSqlParameterSource(params);
KeyHolder keyHolder = new GeneratedKeyHolder();
getNamedParameterJdbcTemplate().update("INSERT INTO " + schema + "waygraphs (name) VALUES (:name)",
sqlParameterSource, keyHolder, new String[] {"id"});
return Long.class.cast(keyHolder.getKey());
}
示例12: insertAndGetKey
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
public Long insertAndGetKey(final String sql, final Object... args) {
final String mSql = initSql(sql);
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(mSql, Statement.RETURN_GENERATED_KEYS);
if (args != null && args.length > 0) {
for (int index = 0; index < args.length; index++) {
ps.setObject((index + 1), args[index]);
}
}
return ps;
}
}, keyHolder);
Long generatedId = keyHolder.getKey().longValue();
return generatedId;
}
示例13: createDefaultAuthzZone
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
private Long createDefaultAuthzZone(final JdbcTemplate jdbcTemplate) {
final String insertZoneSql =
"INSERT INTO authorization_zone (name, description, subdomain) " + "VALUES (?,?,?)";
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(insertZoneSql, new String[] { "id" });
ps.setString(1, "apm-migrated");
ps.setString(2, "APM Migrated Zone from mvp1");
ps.setString(3, "apm-migrated");
return ps;
}
}, holder);
return holder.getKey().longValue();
}
示例14: persist
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Override
public void persist(EventLog eventLog) {
Timestamp now = toSqlTimestamp(Instant.now());
MapSqlParameterSource namedParameterMap = new MapSqlParameterSource();
namedParameterMap.addValue("eventType", eventLog.getEventType());
namedParameterMap.addValue("eventBodyData", eventLog.getEventBodyData());
namedParameterMap.addValue("flowId", eventLog.getFlowId());
namedParameterMap.addValue("created", now);
namedParameterMap.addValue("lastModified", now);
namedParameterMap.addValue("lockedBy", eventLog.getLockedBy());
namedParameterMap.addValue("lockedUntil", eventLog.getLockedUntil());
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
"INSERT INTO " +
" nakadi_events.event_log " +
" (event_type, event_body_data, flow_id, created, last_modified, locked_by, locked_until) " +
"VALUES " +
" (:eventType, :eventBodyData, :flowId, :created, :lastModified, :lockedBy, :lockedUntil)",
namedParameterMap,
generatedKeyHolder
);
eventLog.setId((Integer) generatedKeyHolder.getKeys().get("id"));
}
开发者ID:zalando-nakadi,项目名称:nakadi-producer-spring-boot-starter,代码行数:25,代码来源:EventLogRepositoryImpl.java
示例15: createUser
import org.springframework.jdbc.support.GeneratedKeyHolder; //导入依赖的package包/类
@Override
public int createUser(final CalendarUser userToAdd) {
if (userToAdd == null) {
throw new IllegalArgumentException("userToAdd cannot be null");
}
if (userToAdd.getId() != null) {
throw new IllegalArgumentException("userToAdd.getId() must be null when creating a "+CalendarUser.class.getName());
}
KeyHolder keyHolder = new GeneratedKeyHolder();
this.jdbcOperations.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(
"insert into calendar_users (email, password, first_name, last_name) values (?, ?, ?, ?)",
new String[] { "id" });
ps.setString(1, userToAdd.getEmail());
ps.setString(2, userToAdd.getPassword());
ps.setString(3, userToAdd.getFirstName());
ps.setString(4, userToAdd.getLastName());
return ps;
}
}, keyHolder);
return keyHolder.getKey().intValue();
}