版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010741376/article/details/46637855
-
Spring的JdbcTemplate插入操作返回主键ID的方法:
- /**
- *
- *
- * 增加并且获取主键
- * @param sql sql语句
- * @param params 参数
- * @return 主键
- */
- public Long insertAndGetKey(final String sql, final Student student ) {
- KeyHolder keyHolder = new GeneratedKeyHolder();
- jdbcTemplate.update(new PreparedStatementCreator() {
- public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
- PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
- ps.setString(1, student .getTitle());
- ps.setString(2, student .getContent());
- ps.setString(3, student .getForm());
- ps.setString(4, student
.getSffs());
- ps.setString(5, new Date(student.getTime().getTime()));
- ps.setString(6, student .getBy2());
- ps.setString(7, student .getBy3());
- return ps;
- }
- }, keyHolder);
- Long generatedId = keyHolder.getKey().longValue();
- return generatedId;
- }