Spring Data Jpa 更新表中的20M条记录,并使用spring Boot 为每条记录设置col1 = col2 + col3

o4tp2gmn  于 2024-01-09  发布在  Spring
关注(0)|答案(2)|浏览(279)

更新表中的20M条记录,并使用spring Boot 为每条记录设置col1 = col2 + col3。

  1. try (Connection connection = dataSource.getConnection()) {
  2. String updateQuery = "UPDATE table SET col1 = ? WHERE id = ?";
  3. PreparedStatement preparedStatement = connection.prepareStatement(updateQuery);
  4. for (TableEntity entity : tableEntities) {
  5. preparedStatement.setInt(1, calculate(offersLeadScore)); // Set new col1
  6. preparedStatement.setObject(2, entity.getId());
  7. preparedStatement.addBatch();
  8. }
  9. preparedStatement.executeBatch();`

字符串
上面的方法花费了很多时间来执行和更新表中的所有记录。
如何使用Sping Boot 实现更快的执行?
已尝试JPA的saveAll()及以上方法。无法优化它。
需要一些行业标准的方法来更新一个表中的所有记录更快的方式。

cpjpxq1n

cpjpxq1n1#

尝试这种方法,它通过使用名为TableService的Sping Boot 服务来有效地更新数据库表中2000万条记录的大数据集。updateCol 1ForTable函数包含主要操作。此方法构建SQL更新查询,使用记录的id作为引用,将col 1的新值计算为每条记录的col 2和col 3之和。下面是代码;

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.jdbc.core.BatchPreparedStatementSetter;
  3. import org.springframework.jdbc.core.JdbcTemplate;
  4. import org.springframework.stereotype.Service;
  5. import java.sql.PreparedStatement;
  6. import java.sql.SQLException;
  7. import java.util.List;
  8. @Service
  9. public class TableService {
  10. private final JdbcTemplate jdbcTemplate;
  11. @Autowired
  12. public TableService(JdbcTemplate jdbcTemplate) {
  13. this.jdbcTemplate = jdbcTemplate;
  14. }
  15. public void updateCol1ForTable(List<TableEntity> tableEntities) {
  16. String updateQuery = "UPDATE your_table_name SET col1 = col2 + col3 WHERE id = ?";
  17. jdbcTemplate.batchUpdate(updateQuery, new BatchPreparedStatementSetter() {
  18. @Override
  19. public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
  20. preparedStatement.setLong(1, tableEntities.get(i).getId());
  21. }
  22. @Override
  23. public int getBatchSize() {
  24. return tableEntities.size();
  25. }
  26. });
  27. }
  28. }

字符串
要有效地批量更新记录,请从服务层或控制器调用此函数。
希望能成功:)

展开查看全部
6qqygrtg

6qqygrtg2#

为什么?为什么?您最多只是引入了一个维护难题。或col 3被更新,并且每次插入一行。一个更好的解决方案是在select上执行计算。这是对select的一次维护。如果出于某种原因,您认为需要存储派生结果,那么定义col1作为生成的。首先删除列,然后重新添加它:(demo here)

  1. alter table <your_table_name> drop col1;
  2. alter table <your_table_name>
  3. add col1 bigint
  4. generated always as (col2::bigint + col3::bigint) stored;

字符串
初始运行/设置不会很快。但代价是您无需进行维护,并且当添加行时以及每当col2' and/or col 3 '更新时,col1的值会自动计算。最初或之后不需要额外的维护。

相关问题