1、先介绍一下java.sql.Connection接口提供的三个在执行插入语句后可取的自动生成的主键的方法:
//第一个是
PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException;
其中autoGenerateKeys 有两个可选值:Statement.RETURN_GENERATED_KEYS、Statement.NO_GENERATED_KEYS
//第二个是
PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException;
//第三个是
PreparedStatement prepareStatement(String sql, String[] columnNames)throws SQLEception;

//批量插入Person实例,返回每条插入记录的主键值
public int[] insert(List<Person> persons) throws SQLException{String sql = "insert into test_table(name) values(?)" ;int i = 0 ;int rowCount = persons.size() ;int[] keys = new int[rowCount] ;DataSource ds = SimpleDBSource.getDB() ;Connection conn = ds.getConnection() ;//根据主键列名取得自动生成主键值String[] columnNames= {"id"} ;PreparedStatement pstmt = conn.prepareStatement(sql, columnNames) ;Person p = null ;for (i = 0 ; i < rowCount ; i++){p = persons.get(i) ;pstmt.setString(1, p.getName()) ;pstmt.addBatch();}pstmt.executeBatch() ;//取得自动生成的主键值的结果集ResultSet rs = pstmt.getGeneratedKeys() ;while(rs.next() && i < rowCount){keys[i] = rs.getInt(1) ;i++ ;}return keys ;
}

2、下面是Spring的JDBCTemplate实例

插入一条记录返回刚插入记录的id

Java代码

public int addBean(final Bean b){   final String strSql = "insert into buy(id,c,s,remark,line,cdatetime," + "c_id,a_id,count,type) values(null,?,?,?,?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); this.getJdbcTemplate().update( new PreparedStatementCreator(){ public java.sql.PreparedStatement createPreparedStatement(Connection conn) throws SQLException{ int i = 0; java.sql.PreparedStatement ps = conn.prepareStatement(strSql); ps = conn.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS); ps.setString(++i, b.getC()); ps.setInt(++i,b.getS() ); ps.setString(++i,b.getR() ); ps.setString(++i,b.getline() ); ps.setString(++i,b.getCDatetime() ); ps.setInt(++i,b.getCId() ); ps.setInt(++i,b.getAId()); ps.setInt(++i,b.getCount()); ps.setInt(++i,b.getType()); return ps; } }, keyHolder); return keyHolder.getKey().intValue(); } public int addBean(final Bean b){ final String strSql = "insert into buy(id,c,s,remark,line,cdatetime," + "c_id,a_id,count,type) values(null,?,?,?,?,?,?,?,?,?)"; KeyHolder keyHolder = new GeneratedKeyHolder(); this.getJdbcTemplate().update( new PreparedStatementCreator(){ public java.sql.PreparedStatement createPreparedStatement(Connection conn) throws SQLException{ int i = 0; java.sql.PreparedStatement ps = conn.prepareStatement(strSql); ps = conn.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS); ps.setString(++i, b.getC()); ps.setInt(++i,b.getS() ); ps.setString(++i,b.getR() ); ps.setString(++i,b.getline() ); ps.setString(++i,b.getCDatetime() ); ps.setInt(++i,b.getCId() ); ps.setInt(++i,b.getAId()); ps.setInt(++i,b.getCount()); ps.setInt(++i,b.getType()); return ps; } }, keyHolder); return keyHolder.getKey().intValue(); } 2.批量插入数据 Java代码 public void addBuyBean(List<BuyBean> list) { final List<BuyBean> tempBpplist = list; String sql="insert into buy_bean(id,bid,pid,s,datetime,mark,count)" + " values(null,?,?,?,?,?,?)"; this.getJdbcTemplate().batchUpdate(sql,new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return tempBpplist.size(); } @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setInt(1, tempBpplist.get(i).getBId()); ps.setInt(2, tempBpplist.get(i).getPId()); ps.setInt(3, tempBpplist.get(i).getS()); ps.setString(4, tempBpplist.get(i).getDatetime()); ps.setString(5, tempBpplist.get(i).getMark()); ps.setInt(6, tempBpplist.get(i).getCount()); } }); } public void addBuyBean(List<BuyBean> list) { final List<BuyBean> tempBpplist = list; String sql="insert into buy_bean(id,bid,pid,s,datetime,mark,count)" + " values(null,?,?,?,?,?,?)"; this.getJdbcTemplate().batchUpdate(sql,new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return tempBpplist.size(); } @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setInt(1, tempBpplist.get(i).getBId()); ps.setInt(2, tempBpplist.get(i).getPId()); ps.setInt(3, tempBpplist.get(i).getS()); ps.setString(4, tempBpplist.get(i).getDatetime()); ps.setString(5, tempBpplist.get(i).getMark()); ps.setInt(6, tempBpplist.get(i).getCount()); } }); } 3.批量插入并返回批量id 注:由于JDBCTemplate不支持批量插入后返回批量id,所以此处使用jdbc原生的方法实现此功能 Java代码 public List<Integer> addProduct(List<ProductBean> expList) throws SQLException { final List<ProductBean> tempexpList = expList; String sql="insert into product(id,s_id,status,datetime," + " count,o_id,reasons" + " values(null,?,?,?,?,?,?)"; DbOperation dbOp = new DbOperation(); dbOp.init(); Connection con = dbOp.getConn(); con.setAutoCommit(false); PreparedStatement pstmt = con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS); for (ProductBean n : tempexpList) { pstmt.setInt(1,n.getSId()); pstmt.setInt(2,n.getStatus()); pstmt.setString(3,n.getDatetime()); pstmt.setInt(4,n.getCount()); pstmt.setInt(5,n.getOId()); pstmt.setInt(6,n.getReasons()); pstmt.addBatch(); } pstmt.executeBatch(); con.commit(); ResultSet rs = pstmt.getGeneratedKeys(); //获取结果 List<Integer> list = new ArrayList<Integer>(); while(rs.next()) { list.add(rs.getInt(1));//取得ID } con.close(); pstmt.close(); rs.close(); return list; }

Spring利用JDBCTemplate实现批量插入和返回id相关推荐

  1. spring JDBCTemplate实现批量插入及返回id

    1.插入一条记录返回刚插入记录的id public int addBean(final Bean b){ final String strSql = "insert into buy(id, ...

  2. mybatis的插入与批量插入的返回ID的原理

    文章目录 背景 底层调用方法 单个对象插入 直接保存实体的对象作为参数传入(给伪代码示例) 多个对象,实体对象作为其中一个对象传入 列表批量插入 直接保存实体的对象作为参数传入(给伪代码示例) 多个对 ...

  3. Mybatis批量插入,返回主键ID不成功,巨坑

    一.场景说明 批量插入,返回主键ID报错 org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibati ...

  4. mysql测试数据100w_利用MySQL存储过程批量插入100W条测试数据

    这里将告诉您利用MySQL存储过程批量插入100W条测试数据,具体完成步骤:DROP PROCEDURE IF EXISTS insert_batch; CREATE PROCEDURE insert ...

  5. mysql批量插入没有返回主键id

    在大批量新增数据的时候往往会采用批量插入来提高效率,但是经常遇到没有返回主键的情况. 一般会有以下几种可能: 1.升级Mybatis版本到3.3.1.官方在这个版本中加入了批量新增返回主键id的功能 ...

  6. 利用CAD VBA批量插入多段线

    CAD VBA批量插入多段线,利用一维动态数组 Sub aa() '定义一个运行过程 Dim arr() As Double '定义一个空的动态数组 m = 4 '随便定一个值 nn = Array( ...

  7. spring boot + mybatis实现批量插入数据

    场景描述:前端以List的形式传入多条待插入数据,调用mybatis-generator自动生成的insert接口一次只能插入一条数据,当然可以写一个for循环一条条插入,但感觉效率太低:所以尝试下一 ...

  8. oracle批量插入并且返回自增主键_mybatis + (oracle)实现主键自增 + 插入数据并返回主键...

    一.实现主键自增 在oracle数据库中,主键并没有办法自动增长,无法使用insert对应的useGeneratedKeys和keyProperty属性自动返回增加的主键. 要实现自增需要修改 ID列 ...

  9. oracle批量插入并且返回自增主键_oracle 自增主键实现批量更新和增加sql

    增加: 方案1 INSERT INTO WF_TASKTEMP_DEALSTAFF (DEAL_ID, TEMP_ID, STAFF_ID,DEAL_TYPE, STATUS) SELECT WF_T ...

最新文章

  1. 单载波调制和OFDM调制比较
  2. Introduction | Elasticsearch权威指南(中文版) | 好的博文地址|官方资源所在位置
  3. Android获取当前位置的三种方式及其使用方法
  4. Angular 内容投影 content projection 关于选择器问题的单步调试
  5. iframe 高度根据子页面来确定
  6. python连接wifi_Python3控制win10连接wifi热点
  7. 安卓双屏折叠手机!看了微软时隔四年发布的手机 手里的iPhone差点掉地上
  8. 生产环境下 RocketMQ 为什么不能开启自动创建主题?
  9. access数据库拆分的用途_在Access中手动拆分数据库
  10. 世界首富马斯克的编程水平怎么样?
  11. Execl同时冻结行和列
  12. win10计算机如何禁用签名,win10系统禁用数字签名的设置方案
  13. 将image对象转成BufferedImage
  14. 2019 年第 32 周 DApp 影响力排行榜 | TokenInsight
  15. 2021年终总结及2022年展望
  16. Android视图绑定,设置控件点击事件不生效
  17. MySQL为什么lsof会看到这么多临时文件
  18. ArcGIS Pro添加在线遥感底图
  19. Java 递归查询部门树形结构数据
  20. vim编辑器退不出来的问题

热门文章

  1. myeclipse安装、导入一个项目、解决2个程序错误、解决运行错误、运行项目
  2. VC++调试技巧学习总结
  3. VC++源码分析 - 中国象棋源码分析
  4. 搞定JSP第一个Servlet例子并且还是手动编译
  5. 51单片机学习笔记(清翔版)(21)——ADDA数模转换
  6. Java开发小技巧(五):HttpClient工具类
  7. 节流函数(throttle)的原理
  8. Limesurvey-2.55 (Ubuntu 16.04)
  9. excel数据库_中琅条码打印软件数据库连接详解
  10. Baseline needs more love