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要使用此功能需要在配置文件中显示声明两个属性即可:
随机推荐
- ubuntu下lamp配置
apache 在Ubuntu Linux上用 apt-get install apache2 安装Apache2后,竟然发现没有httpd.conf(位于/etc/apache2目录) Ubuntu的 ...
- golang学习之旅:使用go语言操作mysql数据库
1.下载并导入数据库驱动包 官方不提供实现,先下载第三方的实现,点击这里查看各种各样的实现版本.这里选择了Go-MySQL-Driver这个实现.地址是:https://github.com/go-s ...
- 【BZOJ-4569】萌萌哒 ST表 + 并查集
4569: [Scoi2016]萌萌哒 Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 459 Solved: 209[Submit][Status] ...
- java时间和日期类型
在java中,代表时间和日期的类型包括:java.util.Date和java.util.Calendar,此外,在JDBC API中还提供了3个扩展类,java.UtilDate类的子类:java. ...
- wpf listview 换行
<ListView Name="listView1" VerticalAlignment="Top" Height="600" Ma ...
- BZOJ2440 [中山市选2011]完全平方数
本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...
- NuGet打包推送批处理以及MSBuild(通用版)
使用时注意每个批处理里面的依赖工具路径指向 源码:https://github.com/easonjim/NuGetRun bug提交:https://github.com/easonjim/NuGe ...
- selenium.Phantomjs设置浏览器请求头
from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCap ...
- HTML5学习总结-04 音频&视频播放
一 音频播放 1 Audio(音频) HTML5提供了播放音频文件的标准 2 control(控制器) control属性攻添加播放,暂停和音量空间. 3 标签定义声音 <audio> 例 ...
- 1 NFS高可用解决方案之DRBD+heartbeat搭建
preface NFS作为业界常用的共享存储方案,被众多公司采用.我司也不列外,使用NFS作为共享存储,为前端WEB server提供服务,主要存储网页代码以及其他文件. 高可用方案 说道NFS,不得 ...