Spring利用JDBCTemplate实现批量插入和返回id
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的更多相关文章
- mybatis的插入与批量插入的返回ID的原理
目录 背景 底层调用方法 单个对象插入 列表批量插入 完成 背景 最近正在整理之前基于mybatis的半ORM框架.原本的框架底层类ORM操作是通过StringBuilder的append拼接的,这次 ...
- spring data jpa开启批量插入、批量更新
spring data jpa开启批量插入.批量更新 原文链接:https://www.cnblogs.com/blog5277/p/10661096.html 原文作者:博客园--曲高终和寡 *** ...
- ibatis插入数据返回ID的方法
ibatis插入数据返回ID的方法 主要就是利用seelctkey来获取这个ID值,但是oracle和mysql的区别还是很大的 oracle的用法 <insert id="inser ...
- mybatis批量插入并返回主键(序列)-oracle
需求:批量插入数据,并返回每条数据的主键(序列),因为这里是采用序列生成唯一的主键的, 其实oracle批量 插入操作有几种,网上百度都是有相关资源的.但是笔者现在的需求是,不仅批量插入数据后,并返回 ...
- Mybatis(spring)(多个参数)(插入数据返回id)
一. 1.两个参数都是int类型() 例子: 1 < select id="searchClassAllNum" resultType="int"> ...
- 利用MySQL存储过程批量插入100W条测试数据
DROP PROCEDURE IF EXISTS insert_batch; CREATE PROCEDURE insert_batch() BEGIN ; loopname:LOOP '); ; T ...
- MySQL插入数据返回id
按照应用需要,常常要取得刚刚插入数据库表里的记录的ID值,在MYSQL中可以使用LAST_INSERT_ID()函数,在MSSQL中使用 @@IDENTITY.挺方便的一个函数.但是,这里需要注意的是 ...
- MyBatis插入并返回id技巧
1, 使用返回插入id的值,这个值即是当前插入的id
- mybatis 插入数据返回ID
hibernate中插入数据后会返回插入的数据的ID,mybatis要使用此功能需要在配置文件中显示声明两个属性即可:
随机推荐
- bzoj3295: [Cqoi2011]动态逆序对(树套树)
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...
- C++开发的数据库连接查询修改小工具
项目相关地址 源码:https://github.com/easonjim/SQL_Table_Tool bug提交:https://github.com/easonjim/SQL_Table_Too ...
- 关于 htonl 和 ntohl 的实现
因为需要直接处理一个网络字节序的 32 位 int,所以,考虑用自己写的还是系统函数效率更高.然后又了下面的了解. 首先是系统函数 htonl ,我在 kernel 源码 netinet/in.h 找 ...
- JDBC连接简介
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; ...
- 【Alpha版本】测试文档
App测试点 UI测试 测试各界面控件布局.总体色调.风格是否能够给用户良好的使用感. 文字是否正确,图文符合,文字与图片的组合是否够美观. 操作是否友好,是否易于操作,是否繁琐,存在无用操作. 配图 ...
- jQuery知识点总结(第二天)
今天继续从我的笔记上面搬运.我们不产生知识,只是知识的搬运工. 内容过滤选择器: ○ 内容选择过滤器 $("div ...
- CSS--结构和层叠
选择器的特殊性 特殊性值表述为4个部分,如0,0,0,0.具体特殊性如下所示: 举例说明一下: 通配符选择器的特殊性 通配符选择器其特殊性为0,0,0,0 !important重要性 大家都知道内联样 ...
- Struts2-----面试题汇总
1.struts2框架中,从用户发出请求到获得响应整个过程的流转图 FilterDispatcher --> ActionProxy-->Configuration Manager--&g ...
- Python与C++结构体交互
需求:根据接口规范,实现与服务端的数据交互 服务端结构体分包头.包体.包尾 包头C++结构体示例如下 typedef struct head { BYTE string1; BYTE string2; ...
- mybatis的批量删除
公司工程用的是Mybatis的example的类,自动生成了对数据库的操作,批量操作的今天用到了,两种方式,一种需要拓展它生成的类,另一种自带的. 批量删除的id是以集合List传递 id以List& ...