//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();
}
});
}
//insert batch example with sql
public void insertbatchsql(final string sql){
getjdbctemplate().batchupdate(new string[]{sql});
}
<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);
}
}