Spring 专题
专题目录
您的位置:java > Spring专题 > Spring SimpleJdbcTemplate batchUpdate()实例
Spring SimpleJdbcTemplate batchUpdate()实例
作者:--    发布时间:2019-11-20 10:22:26
在本教程中,我们将向你展示如何在了simplejdbctemplate类使用batchupdate()。详细请参见 在simplejdbctemplate 类的 batchupdate()示例 。
//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);        
}
或者,你可以直接执行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="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);
      
    }
}
在本例中,插入三个顾客的记录,并批量更新所有客户的名字。


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