Spring JdbcTemplate.batchUpdate 例子
程序员文章站
2022-04-25 08:28:58
...
最近再看开源项目阿里巴巴的数据库同步项目Otter https://github.com/alibaba/otter的时候,看到里面很多时候都使用了JdbcTemplate 来对数据进行相应的数据操作。
这里写一个使用批操作的batchUpdate()的例子,来自spring-jdbctemplate-batchupdate-example
需要使用批操作来操作数据库的数据。
第一种用法:
//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();
}
});
}
第二种用法(当然你可以直接运行sql语句):
//insert batch example with SQL
public void insertBatchSQL(final String sql){
getJdbcTemplate().batchUpdate(new String[]{sql});
}
Spring的配置文件
<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.mkyong.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/mkyongjava" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
</beans>
运行:
package com.mkyong.common;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.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, "mkyong1",21);
Customer customer3 = new Customer(2, "mkyong2",22);
Customer customer2 = new Customer(3, "mkyong3",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);
}
}
上一篇: Tim群在哪?腾讯Tim查看群组方法
下一篇: 微信小程序客服怎么设置绑定微信客服?
推荐阅读
-
spring boot整合spring-kafka实现发送接收消息实例代码
-
详解Spring Boot下Druid连接池的使用配置分析
-
c# 删除所有的空文件夹的小例子
-
详解SpringBoot之集成Spring AOP
-
c# 开机启动项的小例子
-
WinForm DataGridView控件隔行变色的小例子
-
spring-cloud入门之spring-cloud-config(配置中心)
-
使用 Spring Boot 2.0 + WebFlux 实现 RESTful API功能
-
Spring声明式事务和@Aspect的拦截顺序问题的解决
-
详解Spring Cloud Hystrix断路器实现容错和降级