/**
* 预编译+批处理模式更新数据
* */
@SuppressWarnings("deprecation")
private boolean batchExecuteInsertTest(){
boolean isok = true;
Session session = this.getHibernateTemplate().getSessionFactory().openSession();
Connection conn=null;//连接
PreparedStatement pstm=null; //预编译语句
String pstmSql = null;
Savepoint sp = null;
try {
conn = session.connection();
conn.setAutoCommit(false); // 设置不自动提交
sp = conn.setSavepoint();//设置回滚点
pstmSql = "insert into test(id,name) values (?,?)";
pstm = conn.prepareStatement(pstmSql);
int recordNum = 1; // 计数器
int commit_size = 2;// 每次提交记录数2
pstm.setString(1, "5");//
pstm.setString(2, "5——列数据");
pstm.addBatch();
int total = 5;
//循环队列
for (int i = 1; i <= total; i++) {
recordNum++; // 计数
pstm.setString(1, i+"");//
pstm.setString(2, i+"列数据");//
pstm.addBatch();
// 每1000次提交一次
if (recordNum % commit_size == 0) {// 可以设置不同的大小;如50,100,500,1000等等
pstm.executeBatch();
conn.commit();
pstm.clearBatch();
conn.setAutoCommit(false);
pstm = conn.prepareStatement(pstmSql);
}
}
if (recordNum % commit_size != 0) { //执行剩余的批处理
pstm.executeBatch();
conn.commit();
}
} catch (Exception e) {
isok = false;
e.printStackTrace();
try {
if (conn != null) { // 回滚事务
conn.rollback(sp);//回滚到那个事务点上去
conn.commit();
}
} catch(Exception e2){
}
}finally{
try {
if (pstm != null) {
pstm.close();
pstm = null;
}
if (conn != null) {
conn.close();
conn = null;
}
if (session != null) {
session.close();
session = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return isok;
}
我设置2条记录进行提交,当执行到第6条语句时,由于主键唯一性,无法执行。却没有事务回滚,不知道怎么回事?希望各位高手指点!