橘子味的心
标题:Spring SimpleJdbcTemplate batchUpdate()实例

在本教程中,我们将向你展示如何在了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.yiibai.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/yiibai" />
		<property name="username" value="root" />
		<property name="password" value="" />
	</bean>
	
</beans>

执行它

package com.yiibai.common;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yiibai.customer.dao.CustomerDAO;
import com.yiibai.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, "yiibai1",21);
        Customer customer3 = new Customer(2, "yiibai2",22);
        Customer customer2 = new Customer(3, "yiibai3",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);
      
    }
}
在本例中,插入三个顾客的记录,并批量更新所有客户的名字。


分类