<insert id="add" parameterType="vo.Category" useGeneratedKeys="true" keyProperty="id"> insert into category (name_zh, parent_id, show_order, delete_status, description ) values (#{nameZh,jdbcType=VARCHAR}, #{parentId,jdbcType=SMALLINT}, #{showOrder,jdbcType=SMALLINT}, #{deleteStatus,jdbcType=BIT}, #{description,jdbcType=VARCHAR} ) </insert> 或 <insert id="add" parameterType="vo.Category"> <selectKey resultType="java.lang.Short" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() AS id </selectKey> insert into category (name_zh, parent_id, show_order, delete_status, description ) values (#{nameZh,jdbcType=VARCHAR}, #{parentId,jdbcType=SMALLINT}, #{showOrder,jdbcType=SMALLINT}, #{deleteStatus,jdbcType=BIT}, #{description,jdbcType=VARCHAR} ) </insert>
/** * 增加并且获取主键 * @param sql sql语句 * @param params 参数 * @return 主键 */ public Long insertAndGetKey(final String sql, final SmsBean smsbean) { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { //String sql_sms = "insert into sms(title,content,date_s,form,sffs,by1,by2,by3) values (?,?,'"+dates+"',?,?,?,?,?)"; PreparedStatement ps = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); ps.setString(1, smsbean.getTitle()); ps.setString(2, smsbean.getContent()); ps.setString(3, smsbean.getForm()); ps.setString(4, smsbean.getSffs()); /* * by1 存放的是 草稿主人的ID * 当消息为发送。清楚by1的ID */ ps.setString(5, ""); ps.setString(6, smsbean.getBy2()); ps.setString(7, smsbean.getBy3()); return ps; } }, keyHolder); Long generatedId = keyHolder.getKey().longValue(); return generatedId; }