你可以通过创建批处理PreparedStatement#addBatch()
并通过执行PreparedStatement#executeBatch()
。
这是一个启动示例:
public void save(List<Entity> entities) throws sqlException {
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement(sql_INSERT);
) {
int i = 0;
for (Entity entity : entities) {
statement.setString(1, entity.getSomeproperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
因为某些JDBC驱动程序和/或DB可能对批处理长度有限制,所以它每1000个项目执行一次。