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要使用此功能需要在配置文件中显示声明两个属性即可:
随机推荐
- struts2 action 页面跳转
struts2 action 页面跳转 标签: actionstruts2redirect 2013-11-06 16:22 20148人阅读 评论(0) 收藏 举报 (1)type="di ...
- Oracle触发器实例(网搜)
触发器使用教程和命名规范 目 录触发器使用教程和命名规范 11,触发器简介 12,触发器示例 23,触发器语法和功能 34,例一:行级触发器之一 45,例二:行级触发器之二 46,例三:INSTEA ...
- HDU2298 Toxophily
本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...
- css中import与link用法区别
方式:引入CSS的方法有两种,一种是@import,一种是link @import url('地址');//注意,这种方式可以放在页面也可以放在css文件中<link href="地址 ...
- ZOJ2314 Reactor Cooling
Reactor Cooling Time Limit: 5 Seconds Memory Limit: 32768 KB Special Judge The terrorist g ...
- 洛谷P2746 [USACO5.3]校园网Network of Schools
题目描述 一些学校连入一个电脑网络.那些学校已订立了协议:每个学校都会给其它的一些学校分发软件(称作“接受学校”).注意即使 B 在 A 学校的分发列表中, A 也不一定在 B 学校的列表中. 你要写 ...
- dedecms /member/resetpassword.php SQL Injection Vul
catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 DEDEcms SQL注入漏洞导致可以修改任意用户密码 2. 漏洞触发条 ...
- HttpClient + Jsoup模拟登录教务处并获取课表
1.概述 最近想做一个校园助手类的APP,由于第一次做,所以打算先把每个功能单独实现,防止乱了阵脚.利用教务处登录获取课表和成绩等是一个基本功能,所以以获取课表为例实现了这个功能.完整代码点这里,尝试 ...
- os和sys模块
sys模块 sys模块主要是用于提供对python解释器相关的操作 函数 sys.argv #命令行参数List,第一个元素是程序本身路径 sys.path #返回模块的搜索路径,初始化时使用PYTH ...
- AC 自动机
AC自动机(Aho-Corasick Automata)是经典的多模式匹配算法.从前我学过这个算法,但理解的不深刻,现在已经十分不明了了.现在发觉自己对大部分算法的掌握都有问题,决定重写一系列博客把学 ...