//insert batch example public void insertbatch(final list<customer> customers){ string sql = "insert into customer " + "(cust_id, name, age) values (?, ?, ?)"; list<object[]> parameters = new arraylist<object[]>(); for (customer cust : customers) { parameters.add(new object[] {cust.getcustid(), cust.getname(), cust.getage()} ); } getsimplejdbctemplate().batchupdate(sql, parameters); }
//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="customersimpledao" class="com.h3.customer.dao.impl.simplejdbccustomerdao"> <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/h3" /> <property name="username" value="root" /> <property name="password" value="" /> </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 customersimpledao = (customerdao) context.getbean("customersimpledao"); 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); customersimpledao.insertbatch(customers); string sql = "update customer set name ='batchupdate'"; customersimpledao.insertbatchsql(sql); } }