Spring 专题
专题目录
您的位置:java > Spring专题 > Spring JdbcTemplate batchUpdate() 实例
Spring JdbcTemplate batchUpdate() 实例
作者:--    发布时间:2019-11-20
在某些情况下,可能需要将一批记录插入到数据库中。如果你对每条记录调用一个插件的方法,sql语句将被重复编译,造成系统缓慢进行。
在上述情况下,你可以使用 jdbctemplate batchupdate()方法来执行批量插入操作。用这种方法,该语句只被编译一次,执行多次。
详见 jdbctemplate 类的 batchupdate()示例。
//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();
	}
  });
}
或者,可以直接执行sql。
//insert batch example with sql
public void insertbatchsql(final string sql){
		
	getjdbctemplate().batchupdate(new string[]{sql});
		
}
spring 的 bean 配置文件
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
	xsi:schemalocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="customerdao" class="com.h3.customer.dao.impl.jdbccustomerdao">
		<property name="datasource" ref="datasource" />
	</bean>
	
	<bean id="datasource" 
        class="org.springframework.jdbc.datasource.drivermanagerdatasource">

		<property name="driverclassname" value="com.mysql.jdbc.driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/h3java" />
		<property name="username" value="root" />
		<property name="password" value="password" />
	</bean>
	
</beans>

执行它

package com.h3.common;

import java.util.arraylist;
import java.util.list;

import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
import com.h3.customer.dao.customerdao;
import com.h3.customer.model.customer;

public class app 
{
    public static void main( string[] args )
    {
    	applicationcontext context = 
    		new classpathxmlapplicationcontext("spring-customer.xml");
    	 
        customerdao customerdao = (customerdao) context.getbean("customerdao");
        customer customer1 = new customer(1, "h31",21);
        customer customer3 = new customer(2, "h32",22);
        customer customer2 = new customer(3, "h33",23);
  
        list<customer>customers = new arraylist<customer>();
        customers.add(customer1);
        customers.add(customer2);
        customers.add(customer3);
        
        customerdao.insertbatch(customers);

        string sql = "update customer set name ='batchupdate'";
        customerdao.insertbatchsql(sql);
      
    }
}
在本例中,插入三条顾客的记录,并批量更新所有客户的名字。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册