Spring中JDBC插入数据后获得该记录的ID

  Spring为自增长主键值数据库中插入数据后,获得该插入数据的ID的代码示例:
	public void addForum(final Forum forum) {
		final String sql = "INSERT INTO t_forum(forum_name, forum_desc) VALUES(?,?)";
		KeyHolder keyHolder = new GeneratedKeyHolder();
		getJdbcTemplate().update(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection conn) {
				PreparedStatement ps = conn.prepareStatement(sql);
				ps.setString(1, forum.getForumName());
				ps.setString(2, forum.getForumDesc());
				return ps;
			}
		}, keyHolder);
		forum.setForumId(keyHolder.getKey().intValue());
	}

你可能感兴趣的:(spring,sql,jdbc)