java - NamedParameterJdbcTemplate 的 update() 和 batchUpdate() 方法之间的性能和限制问题

标签 java spring

我想知道何时使用 Spring 框架的 NamedParameterJdbcTemplate 类中的 update()bacthUpdate() 方法。

update() 有行数限制吗?有多少行可以处理 update() 而不会出现性能问题或挂起我的数据库?从多少行开始,batchUpdate() 获得了良好的性能?

谢谢。

最佳答案

下面是我的观点:

when to use update() or bacthUpdate() method from NamedParameterJdbcTemplate class of Spring framework

只要需要同时执行多个sql,就应该使用bacthUpdate()

Is there any row limitation for update()?

这应该取决于您使用的DB。但是我还没有遇到更新的行限制。当然,更新几行比更新多行更快。(例如,UPDATE ... WHERE id=1 vs UPDATE ... WHERE id > 1)。

How many rows can handle update() without having performance issues or hanging my db?

这还不确定。这取决于您使用的DB机器性能等。如果您想知道确切的结果,您可以查看DB Vendor's Benchmark ,或者你可以通过一些测试来衡量它。

Starting from how many rows batchUpdate() is getting good performance?

事实上,batchUpdate() 通常用于批处理 INSERTUPDATEDELETE,这将提高很多性能。比如:

批量插入:

SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(employees.toArray());
int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch);
return updateCounts;

批量更新:

List<Object[]> batch = new ArrayList<Object[]>();
    for (Actor actor : actors) {
        Object[] values = new Object[] {
                actor.getFirstName(),
                actor.getLastName(),
                actor.getId()};
        batch.add(values);
    }
    int[] updateCounts = jdbcTemplate.batchUpdate(
            "update t_actor set first_name = ?, last_name = ? where id = ?",
            batch);
    return updateCounts;

在内部,batchUpdate()会用到PreparedStatement.addBatch(),可以查看一些spring jdbc tutorial. . 批量操作 以一个“批处理”的方式发送到数据库,而不是一个接一个地发送更新。 一次发送一批更新到数据库,比一个接一个地发送,等待每个更新完成要快。发送一批更新(仅 1 次往返)涉及的网络流量较少,并且数据库可能能够并行执行一些更新。此外,当您使用 batchUpdate()batchUpdate() 时,DB 驱动程序 必须支持批量操作 t 在一笔交易中违约。

您可以查看更多详细信息:

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html#jdbc-advanced-jdbc http://tutorials.jenkov.com/jdbc/batchupdate.html#batch-updates-and-transactions

希望你能有所帮助。

关于java - NamedParameterJdbcTemplate 的 update() 和 batchUpdate() 方法之间的性能和限制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36473957/

相关文章:

java - 确定 Java.awt.Rectangle 是否包含 Java.awt.Color

java - 当磁盘存储已满时 Glide 会做什么?

java - 在线程池中重用 Runnable 有意义吗?

java - 无法从 START_OBJECT token 中反序列化 java.util.ArrayList 的实例

java - Spring Data/Hibernate - 传播生成的 key

java - spring-boot中的@ControllerAdvice注释是什么,为什么以及何时使用它?

java - ElasticSearch 将字符串索引为整数,然后在搜索结果中返回整数值

java - File.isDirectory 和 isFile 均为 false

spring - 单元测试 Spring Cloud 服务的策略

java - Axon 事件存储处理 - 读取聚合的所有事件