日期:2014-05-16  浏览次数:20439 次

spring Jdbctemplate返回插入记录的自增Id
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.kjlink.cms.form.model.LabelForm;
import com.kjlink.cms.service.BaseService;

public class ff extends BaseService {

public int insertTable(LabelForm f) throws SQLException,ParseException 
{
String content = f.getSiteId();
final String sql = "insert into TAG_INFO(SITE_ID,NAME,CONTENT) values(?,?,'"+content+"')";
KeyHolder keyHolder = new GeneratedKeyHolder();
getJdbcTemplate().update(
   new PreparedStatementCreator() {
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException 
    {
     PreparedStatement ps = getJdbcTemplate().getDataSource()
       .getConnection().prepareStatement(sql,new String[]{ "SITE_ID" ,"NAME"});
     ps.setString(1, "站点号");
     ps.setString(2, "我的名字");
     return ps;
    }
   }, keyHolder);
   System.out.println("自动插入id============================" + keyHolder.getKey().intValue());
   return keyHolder.getKey().intValue();
}
}

?