Spring JdbcTemplate batchUpdate() example

Spring JdbcTemplate batchUpdate() example,第1张

Spring JdbcTemplate batchUpdate() exampl

In some cases, you may required to insert a batch of records into database in one shot. If you call a single insert method for every record, the SQL statement will be compiled repeatedly and causing your system slow to perform.

In above case, you can use JdbcTemplate batchUpdate() method to perform the batch insert operations. With this method, the statement is compiled only once and executed multiple times.

See batchUpdate() example in JdbcTemplate class.

//insert batch example
public void insertBatch(final List<Customer> customers){
 
  String sql = "INSERT INTO CUSTOMER " +
	"(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
 
  getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
 
	@Override
	public void setValues(PreparedStatement ps, int i) throws SQLException {
		Customer customer = customers.get(i);
		ps.setLong(1, customer.getCustId());
		ps.setString(2, customer.getName());
		ps.setInt(3, customer.getAge() );
	}
 
	@Override
	public int getBatchSize() {
		return customers.size();
	}
  });
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/2083971.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-07-22
下一篇 2022-07-22

发表评论

登录后才能评论

评论列表(0条)

保存