jdbc批量插入后返回批量id

批量插入并返回批量id(由于JDBCTemplate不支持批量插入后返回批量id,所以此处使用jdbc原生的方法实现此功能)

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;  

}  

 

posted @ 2022-04-25 13:34  1156740846  阅读(732)  评论(0编辑  收藏  举报