第一种是JdbcTemplate:
JdbcTemplate jdbcTemplate1 = new JdbcTemplate(dataSource); final String sql = " INSERT INTO FUND_AGGREGATION_TEMP ( " + " ID, ORDER_NO, BUSINESS_TYPE, TYPE, " + " OFFSET_NUM, CREATE_TIME, UPDATE_TIME ) " + " VALUES ( -2, '1', '1', '1', ?, CURRENT TIMESTAMP, CURRENT TIMESTAMP ) "; KeyHolder keyHolder1 = new GeneratedKeyHolder(); jdbcTemplate1.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { //设置返回的主键字段名 PreparedStatement ps = con.prepareStatement(sql,new String[]{ "ID" }); ps.setLong(1, 0); return ps; } }, keyHolder1); int a = keyHolder1.getKey().intValue(); System.out.println(a); LOG.info("返回主键:"+ a);
第二种NamedParameterJdbcTemplate:
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); final String sql = " INSERT INTO FUND_AGGREGATION_TEMP ( " + " ID, ORDER_NO, BUSINESS_TYPE, TYPE, " + " OFFSET_NUM, CREATE_TIME, UPDATE_TIME ) " + " VALUES ( -2, '1', '1', '1', :offsetNum, CURRENT TIMESTAMP, CURRENT TIMESTAMP ) "; MapSqlParameterSource parameters = new MapSqlParameterSource(); parameters.addValue("offsetNum", 0); KeyHolder keyHolder = new GeneratedKeyHolder(); int autoIncId = 0; jdbcTemplate.update( sql, parameters, keyHolder, new String[] {"ID" }); autoIncId = keyHolder.getKey().intValue(); System.out.println(autoIncId); LOG.info("返回主键:"+ autoIncId);
建议使用第二种,根据参数名设置参数,可读性更好