當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring JdbcTemplate batchUpdate() 实例
生活随笔
收集整理的這篇文章主要介紹了
Spring JdbcTemplate batchUpdate() 实例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在某些情況下,可能需要將一批記錄插入到數據庫中。如果你對每條記錄調用一個插件的方法,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() {@Overridepublic 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() );}@Overridepublic 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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="customerDAO" class="com.yiibai.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/yiibaijava" /><property name="username" value="root" /><property name="password" value="password" /></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 customerDAO = (CustomerDAO) context.getBean("customerDAO");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);customerDAO.insertBatch(customers);String sql = "UPDATE CUSTOMER SET NAME ='BATCHUPDATE'";customerDAO.insertBatchSQL(sql);} } 在本例中,插入三條顧客的記錄,并批量更新所有客戶的名字。 下載代碼 –?http://pan.baidu.com/s/1jGTXfgi總結
以上是生活随笔為你收集整理的Spring JdbcTemplate batchUpdate() 实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你们知道砂之船属于什么性质企业吗?
- 下一篇: Spring SimpleJdbcTem