如题,直接贴代码.
方案一:
int key = 0;
try
{
KeyHolder holder = new GeneratedKeyHolder();
this.getJdbcTemplate().update(new PreparedStatementCreator(){
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException
{
int i = 1;
PreparedStatement ps = con.prepareStatement(SQLConstant.insertAdvert, Statement.RETURN_GENERATED_KEYS); // 主键字段 new String[]{"ADVERTID"}
ps.setString(i++, ad.getName());
ps.setString(i++,ad.getDescr());
ps.setString(i++,ad.getIcon());
ps.setString(i++,ad.getPicture());
ps.setString(i++,ad.getUrl());
ps.setInt(i++,ad.getState());
ps.setDate(i++,DateUtil.sqlDToutilD(ad.getCreatedate()));
ps.setDate(i++,DateUtil.sqlDToutilD(ad.getEffdate()));
ps.setDate(i++,DateUtil.sqlDToutilD(ad.getExpdate()));
ps.setDate(i++,DateUtil.sqlDToutilD(ad.getLastupdatedate()));
ps.setInt(i++,ad.getUser_id());
return ps;
}
},holder);
key = holder.getKey().intValue();
log.debug("insert key is :" + key);
} catch (DataAccessException e)
{
log.error("insert Error!", e);
throw new ServiceException("insert Error",e);
}
return key;
方案二:
SimpleJdbcInsert insertActor =
new SimpleJdbcInsert(this.getJdbcTemplate().getDataSource()).withTableName("表名")
.usingGeneratedKeyColumns("dirid");
Map<String, Object> parameters = new HashMap<String, Object>(2);
parameters.put("NAME", "需要插入的值");
Number newId = insertActor.executeAndReturnKey(parameters);
return newId.intValue();
使用第二种方式的时候需要spring2.5以上的版本才可以.