spring JdbcTemplate一括挿入
2618 ワード
1、大量操作によりデータベースとの接続によって消費される資源を減少させる.
2、JdbcTemplateの量産操作特性は、特定のインターフェースBatch PreparedstantSetterを実現する必要があり、このインターフェースを実現することによって、batUpdate方法に伝えて呼び出される.このインターフェースには二つの方法が必要です.一つはgetBatch Sizeといい、現在大量操作が必要な数量を提供します.もう一つの方法は、あなたがprepared statementにパラメータを設定することを許可するsetValuesです.この方法は全過程で呼び出される回数は、あなたがgetBatch Sizeで指定したサイズに依存します.
3、例コードは以下の通りです.
2、JdbcTemplateの量産操作特性は、特定のインターフェースBatch PreparedstantSetterを実現する必要があり、このインターフェースを実現することによって、batUpdate方法に伝えて呼び出される.このインターフェースには二つの方法が必要です.一つはgetBatch Sizeといい、現在大量操作が必要な数量を提供します.もう一つの方法は、あなたがprepared statementにパラメータを設定することを許可するsetValuesです.この方法は全過程で呼び出される回数は、あなたがgetBatch Sizeで指定したサイズに依存します.
3、例コードは以下の通りです.
public void storeSalesOrder(List<Report> list) {
System.out.format(" %s ...%n", ip);
final List<Report> reportList = list;
String sql = "insert into sell_order(traceNo, purchaseBatch, terminalNo, sellDate, "
+ "category, weight, price, amount, createDate, status) values(?,?,?,?,?,?,?,?,?,?)";
template.batchUpdate(sql, new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i)throws SQLException {
String[] text1 = StringUtils.stringToArrayCustom(reportList.get(i).text1,"##");
Calendar cal = Calendar.getInstance();
cal.set(reportList.get(i).year, reportList.get(i).month - 1, reportList.get(i).day,
reportList.get(i).hour, reportList.get(i).minute,reportList.get(i).second);
String text4 = reportList.get(i).text4.replace("#", "");
String traceNo = reportList.get(i).text2;
String purchaseBatch = (text1 != null && text1.length != 0)?text1[0].trim():"";
String terminalNo = (text1 != null && text1.length != 0)?text1[1].trim():"";
Date sellDate = cal.getTime();
String category = text4;
double weight = 0d;
double price = 0d;
if(kgFlag){
weight = reportList.get(i).count.doubleValue();
price = reportList.get(i).unitPrice.doubleValue();
}else{
weight = reportList.get(i).count.doubleValue()/2;
price = reportList.get(i).unitPrice.doubleValue()*2;
}
double amount = reportList.get(i).price.doubleValue();
ps.setString(1, traceNo);
ps.setString(2, purchaseBatch);
ps.setString(3, terminalNo);
ps.setTimestamp(4, new Timestamp(sellDate.getTime()));
ps.setString(5, category);
ps.setDouble(6, weight);
ps.setDouble(7, price);
ps.setDouble(8, amount);
ps.setTimestamp(9, new Timestamp(new Date().getTime()));
ps.setInt(10, 0);
}
public int getBatchSize() {
return reportList.size();
}
});
}