You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/17 08:58:39 UTC

(seatunnel) branch gh-readonly-queue/dev/pr-11474-eaa6403658a0c9c1d7d5b5b5f16a24bfc09974eb created (now 42bd53094a)

This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a change to branch gh-readonly-queue/dev/pr-11474-eaa6403658a0c9c1d7d5b5b5f16a24bfc09974eb
in repository https://gitbox.apache.org/repos/asf/seatunnel.git


      at 42bd53094a [Fix][Connector-V2] Fix JDBC batch data error masking (#11474)

This branch includes the following new commits:

     new 42bd53094a [Fix][Connector-V2] Fix JDBC batch data error masking (#11474)

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(seatunnel) 01/01: [Fix][Connector-V2] Fix JDBC batch data error masking (#11474)

Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-11474-eaa6403658a0c9c1d7d5b5b5f16a24bfc09974eb
in repository https://gitbox.apache.org/repos/asf/seatunnel.git

commit 42bd53094a4bb4f6b22134b5239870c7d370456b
Author: Jast <sh...@apache.org>
AuthorDate: Thu Sep 17 08:58:14 2026 +0000

    [Fix][Connector-V2] Fix JDBC batch data error masking (#11474)
    
    Co-authored-by: zhangshenghang <zh...@apache.org>
    Co-authored-by: zhangshenghang <zh...@users.noreply.github.com>
---
 docs/en/connectors/sink/Jdbc.md                    |   6 +-
 docs/en/connectors/sink/Oracle.md                  |   2 +-
 docs/zh/connectors/sink/Jdbc.md                    |   6 +-
 docs/zh/connectors/sink/Oracle.md                  |   2 +-
 .../seatunnel/jdbc/internal/JdbcOutputFormat.java  | 205 +++++++++++--
 .../jdbc/internal/JdbcOutputFormatBuilder.java     |  15 +-
 .../BufferReducedBatchStatementExecutor.java       |  52 ++--
 .../executor/BufferedBatchStatementExecutor.java   |  26 +-
 .../jdbc/sink/AbstractJdbcSinkWriter.java          |   9 +
 .../connectors/seatunnel/jdbc/sink/JdbcSink.java   |   3 +-
 .../seatunnel/jdbc/sink/JdbcSinkWriter.java        | 144 ++++++++-
 .../internal/JdbcOutputFormatBatchCommitTest.java  | 171 +++++++++++
 .../JdbcOutputFormatReconnectSafetyTest.java       | 187 ++++++++++++
 .../jdbc/internal/JdbcOutputFormatTest.java        |  30 +-
 .../jdbc/internal/executor/BufferExecutorTest.java |  12 +-
 ...kWriterSharedPhysicalTableSchemaChangeTest.java |   6 +-
 .../seatunnel/jdbc/sink/JdbcSinkWriterTest.java    | 330 +++++++++++++++++++++
 17 files changed, 1123 insertions(+), 83 deletions(-)

diff --git a/docs/en/connectors/sink/Jdbc.md b/docs/en/connectors/sink/Jdbc.md
index 460091c300..4ede4637bf 100644
--- a/docs/en/connectors/sink/Jdbc.md
+++ b/docs/en/connectors/sink/Jdbc.md
@@ -355,6 +355,10 @@ exactly-once semantics
 
 Automatic transaction commit is enabled by default
 
+For Oracle JDBC sink, SeaTunnel uses manual commit internally even when `auto_commit = true`.
+This keeps a failed batch atomic and avoids masking the original data error with a later duplicate-key error.
+When checkpointing is disabled, the transaction is committed after every successful `batch_size` / `batch_interval_ms` triggered flush, so flushed rows are not held in one unbounded transaction until the writer closes. When checkpointing is enabled, the commit boundary remains the checkpoint.
+
 ### field_ide [String]
 
 The field "field_ide" is used to identify whether the field needs to be converted to uppercase or lowercase when
@@ -570,7 +574,7 @@ When set to `APPEND_VALUES`, SeaTunnel adds the Oracle `APPEND_VALUES` hint to g
 INSERT /*+ APPEND_VALUES */ INTO ...
 ```
 
-This option is only supported for Oracle JDBC sink insert-only writes. It requires `generate_sink_sql = true`, `auto_commit = true`, no custom `query`, no `primary_keys`, `is_exactly_once = false`, and `support_upsert_by_insert_only = false`.
+This option is only supported for Oracle JDBC sink insert-only writes. It requires `generate_sink_sql = true`, `auto_commit = true`, no custom `query`, no `primary_keys`, `is_exactly_once = false`, and `support_upsert_by_insert_only = false`. Oracle sink still uses manual commit internally when writing data.
 
 ### create_index [boolean]
 
diff --git a/docs/en/connectors/sink/Oracle.md b/docs/en/connectors/sink/Oracle.md
index bba97b1a93..21bade39d6 100644
--- a/docs/en/connectors/sink/Oracle.md
+++ b/docs/en/connectors/sink/Oracle.md
@@ -85,7 +85,7 @@ semantics (using XA transaction guarantee).
 | xa_data_source_class_name                 | String  | No       | -                            | The xa data source class name of the database Driver, for example, Oracle is `oracle.jdbc.xa.client.OracleXADataSource`, and<br/>please refer to appendix for other data sources                                                               |
 | max_commit_attempts                       | Int     | No       | 3                            | The number of retries for transaction commit failures                                                                                                                                                                                          |
 | transaction_timeout_sec                   | Int     | No       | -1                           | The timeout after the transaction is opened, the default is -1 (never timeout). Note that setting the timeout may affect<br/>exactly-once semantics                                                                                            |
-| auto_commit                               | Boolean | No       | true                         | Automatic transaction commit is enabled by default                                                                                                                                                                                             |
+| auto_commit                               | Boolean | No       | true                         | Automatic transaction commit is enabled by default. Oracle sink uses manual commit internally even when this is `true`, so failed batches stay atomic and preserve the original data error.                                                     |
 | properties                                | Map     | No       | -                            | Additional connection configuration parameters,when properties and URL have the same parameters, the priority is determined by the <br/>specific implementation of the driver. For example, in MySQL, properties take precedence over the URL. |
 | common-options                            |         | No       | -                            | Sink plugin common parameters, please refer to [Sink Common Options](../common-options/sink-common-options.md) for details                                                                                                                                    |
 | schema_save_mode                          | Enum    | No       | CREATE_SCHEMA_WHEN_NOT_EXIST | Before the synchronous task is turned on, different treatment schemes are selected for the existing surface structure of the target side.                                                                                                      |
diff --git a/docs/zh/connectors/sink/Jdbc.md b/docs/zh/connectors/sink/Jdbc.md
index f5ac84c757..cf422e5b8b 100644
--- a/docs/zh/connectors/sink/Jdbc.md
+++ b/docs/zh/connectors/sink/Jdbc.md
@@ -351,6 +351,10 @@ JDBC `executeBatch` 失败后的重试次数。Exactly-once 模式要求设置
 
 默认启用自动事务提交
 
+对于 Oracle JDBC Sink,即使配置 `auto_commit = true`,SeaTunnel 写入时也会在内部使用手动提交。
+这样可以保证失败批次的原子性,避免原始数据错误被后续的主键重复错误掩盖。
+关闭 checkpoint 时,每次由 `batch_size` / `batch_interval_ms` 触发并成功的批量写入会立即提交事务,避免已刷出的数据一直停留在同一个未结束的事务中直到 writer 关闭;开启 checkpoint 时,提交边界仍然是 checkpoint。
+
 ### field_ide [String]
 
 字段 `field_ide` 用于在从 source 同步到 sink 时,确定字段是否需要转换为大写或小写。'ORIGINAL' 表示不需要转换,'UPPERCASE'
@@ -566,7 +570,7 @@ Oracle 插入模式。默认值为 `CONVENTIONAL`,保持现有 JDBC insert 行
 INSERT /*+ APPEND_VALUES */ INTO ...
 ```
 
-该选项仅支持 Oracle JDBC Sink 的 insert-only 写入。使用时必须配置 `generate_sink_sql = true`、`auto_commit = true`,不能配置自定义 `query`,不能配置 `primary_keys`,并且 `is_exactly_once = false`、`support_upsert_by_insert_only = false`。
+该选项仅支持 Oracle JDBC Sink 的 insert-only 写入。使用时必须配置 `generate_sink_sql = true`、`auto_commit = true`,不能配置自定义 `query`,不能配置 `primary_keys`,并且 `is_exactly_once = false`、`support_upsert_by_insert_only = false`。Oracle Sink 实际写入时仍会在内部使用手动提交。
 
 ### create_index [boolean]
 
diff --git a/docs/zh/connectors/sink/Oracle.md b/docs/zh/connectors/sink/Oracle.md
index 54ae80e83d..e3c4eedd94 100644
--- a/docs/zh/connectors/sink/Oracle.md
+++ b/docs/zh/connectors/sink/Oracle.md
@@ -84,7 +84,7 @@ import ChangeLog from '../changelog/connector-jdbc.md';
 | xa_data_source_class_name    | String  | 否       | -                            | 数据库Driver的xa数据源类名,例如Oracle,是`Oracle.jdbc.xa.client。OracleXADataSource和<br/>请参阅附录了解其他数据源                                                               |
 | max_commit_attempts          | Int     | 否       | 3                            | 事务提交失败的重试次数                                                                                                                                                                                          |
 | transaction_timeout_sec      | Int     | 否       | -1                           | 事务打开后的超时,默认值为-1(永不超时)。请注意,设置超时可能会影响<br/>精确一次语义                                                                                            |
-| auto_commit                  | Boolean | 否       | true                         | 默认情况下启用自动事务提交                                                                                                                                                                                              |
+| auto_commit                  | Boolean | 否       | true                         | 默认情况下启用自动事务提交。Oracle Sink 即使配置为 `true`,实际写入时也会在内部使用手动提交,以保证失败批次的原子性并保留原始数据错误。                                                                                                                                                                                              |
 | properties                   | Map     | 否       | -                            | 其他连接配置参数,当属性和URL具有相同的参数时,优先级由驱动程序的特定实现决定。例如,在MySQL中,属性优先于URL。 |
 | common-options               |         | 否       | -                            | Sink插件常用参数,请参考 [Sink Common Options](../common-options/sink-common-options.md)                                                                                                                                     |
 | schema_save_mode             | Enum    | 否       | CREATE_SCHEMA_WHEN_NOT_EXIST | 在启动同步任务之前,对目标侧的现有表面结构选择不同的处理方案。                                                                                                      |
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java
index ad5c37242f..efc1563366 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormat.java
@@ -18,6 +18,7 @@
 package org.apache.seatunnel.connectors.seatunnel.jdbc.internal;
 
 import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
+import org.apache.seatunnel.common.utils.ExceptionUtils;
 import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcConnectionConfig;
 import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorErrorCode;
 import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException;
@@ -29,7 +30,10 @@ import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 import java.io.Serializable;
+import java.sql.Connection;
+import java.sql.SQLDataException;
 import java.sql.SQLException;
+import java.sql.SQLIntegrityConstraintViolationException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.IdentityHashMap;
@@ -51,10 +55,13 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
 
     private final JdbcConnectionConfig jdbcConnectionConfig;
     private final StatementExecutorFactory<E> statementExecutorFactory;
+    private final boolean commitOnFlush;
 
     private transient E jdbcStatementExecutor;
     private transient int batchCount = 0;
     private transient volatile boolean closed = false;
+    private transient volatile boolean flushFailed = false;
+    private transient volatile boolean commitFailed = false;
     private transient volatile Exception flushException;
     private transient long lastFlushTimeMs;
     private transient boolean failFastOnRowLevelSqlState;
@@ -63,9 +70,18 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
             JdbcConnectionProvider connectionProvider,
             JdbcConnectionConfig jdbcConnectionConfig,
             StatementExecutorFactory<E> statementExecutorFactory) {
+        this(connectionProvider, jdbcConnectionConfig, statementExecutorFactory, false);
+    }
+
+    public JdbcOutputFormat(
+            JdbcConnectionProvider connectionProvider,
+            JdbcConnectionConfig jdbcConnectionConfig,
+            StatementExecutorFactory<E> statementExecutorFactory,
+            boolean commitOnFlush) {
         this.connectionProvider = checkNotNull(connectionProvider);
         this.jdbcConnectionConfig = checkNotNull(jdbcConnectionConfig);
         this.statementExecutorFactory = checkNotNull(statementExecutorFactory);
+        this.commitOnFlush = commitOnFlush;
     }
 
     /** Connects to the target database and initializes the prepared statement. */
@@ -146,11 +162,34 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
         }
     }
 
+    /**
+     * Clears the failure latch only after a failed row batch has been discarded and rolled back.
+     */
+    public synchronized void resetAfterRowError() {
+        if (failFastOnRowLevelSqlState && batchCount == 0 && !commitFailed) {
+            flushFailed = false;
+            flushException = null;
+        }
+    }
+
+    public boolean hasCommitFailed() {
+        return commitFailed;
+    }
+
     public synchronized void setFailFastOnRowLevelSqlState(boolean failFastOnRowLevelSqlState) {
         this.failFastOnRowLevelSqlState = failFastOnRowLevelSqlState;
     }
 
     public synchronized void flush() throws IOException {
+        if (flushException != null) {
+            LOG.warn(
+                    String.format(
+                            "An exception occurred during the previous flush process %s, skipping"
+                                    + " this flush",
+                            ExceptionUtils.getMessage(flushException)));
+            return;
+        }
+
         if (batchCount == 0) {
             LOG.debug("No data to flush.");
             return;
@@ -160,17 +199,49 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
         for (int i = 0; i <= jdbcConnectionConfig.getMaxRetries(); i++) {
             try {
                 attemptFlush();
+                commitAfterFlushIfNeeded();
                 batchCount = 0;
+                flushFailed = false;
+                flushException = null;
                 lastFlushTimeMs = System.currentTimeMillis();
                 break;
             } catch (SQLException e) {
+                recordFlushException(e);
                 LOG.error("JDBC executeBatch error, retry times = {}", i, e);
-                // In row-error handling mode, data/constraint violations (22XXX/23XXX) are
-                // handled per row instead of being retried as transient JDBC failures.
+                // Row-error mode delegates failed data batches to the writer for rollback.
                 if (failFastOnRowLevelSqlState && isRowLevelSqlState(e)) {
                     throw new JdbcConnectorException(
                             CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, e);
                 }
+
+                List<SQLException> sqlExceptions = findSqlExceptions(e);
+                SQLException nonRetryableDataException =
+                        findNonRetryableDataException(sqlExceptions);
+                if (nonRetryableDataException != null) {
+                    boolean connectionValid;
+                    try {
+                        connectionValid = connectionProvider.isConnectionValid();
+                    } catch (SQLException exception) {
+                        LOG.error("JDBC connection validity check failed.", exception);
+                        throw new JdbcConnectorException(
+                                JdbcConnectorErrorCode.CONNECT_DATABASE_FAILED,
+                                "JDBC connection validity check failed",
+                                exception);
+                    }
+                    if (connectionValid) {
+                        LOG.error(
+                                "Flush failed by non-retryable data error. batchCount={}, retry"
+                                        + " times = {}, sqlState={}, errorCode={}",
+                                batchCount,
+                                i,
+                                nonRetryableDataException.getSQLState(),
+                                nonRetryableDataException.getErrorCode(),
+                                e);
+                        throw new JdbcConnectorException(
+                                CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, e);
+                    }
+                }
+
                 if (i >= jdbcConnectionConfig.getMaxRetries()) {
                     throw new JdbcConnectorException(
                             CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, e);
@@ -189,7 +260,7 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
                             exception);
                 }
                 try {
-                    Thread.sleep(sleepMs * i);
+                    sleepBeforeFlushRetry((long) sleepMs * i);
                 } catch (InterruptedException ex) {
                     Thread.currentThread().interrupt();
                     throw new JdbcConnectorException(
@@ -205,6 +276,36 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
         jdbcStatementExecutor.executeBatch();
     }
 
+    /**
+     * Commits the transaction after a successful batch flush when the connection uses manual
+     * commit.
+     *
+     * <p>This is only enabled for the non-XA writer when checkpointing is disabled, so each
+     * batch-size / batch-interval triggered flush carries its own commit boundary instead of
+     * accumulating every flushed batch in one unbounded transaction until close. When checkpointing
+     * is enabled the commit boundary stays at prepareCommit, keeping the existing checkpoint
+     * semantics unchanged.
+     */
+    private void commitAfterFlushIfNeeded() throws SQLException {
+        if (!commitOnFlush) {
+            return;
+        }
+        Connection connection = connectionProvider.getConnection();
+        if (connection != null && !connection.getAutoCommit()) {
+            try {
+                connection.commit();
+            } catch (SQLException e) {
+                commitFailed = true;
+                recordFlushException(e);
+                throw new JdbcConnectorException(
+                        CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                        "JDBC commit after flush failed. The batch commit result is unknown, so"
+                                + " the writer will not retry this batch silently.",
+                        e);
+            }
+        }
+    }
+
     private boolean isRowLevelSqlState(SQLException sqlException) {
         Set<SQLException> visited = Collections.newSetFromMap(new IdentityHashMap<>());
         SQLException current = sqlException;
@@ -230,17 +331,22 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
     }
 
     private void flushBufferedRecords() {
-        if (batchCount > 0) {
+        if (batchCount > 0 && !flushFailed) {
             try {
                 flush();
             } catch (Exception e) {
                 LOG.warn("Writing records to JDBC failed.", e);
+                flushFailed = true;
                 flushException =
                         new JdbcConnectorException(
                                 CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
                                 "Writing records to JDBC failed.",
                                 e);
             }
+        } else if (batchCount > 0) {
+            LOG.warn(
+                    "Skip flushing buffered JDBC records during close because the previous flush"
+                            + " failed.");
         }
     }
 
@@ -265,6 +371,77 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
                 && (System.currentTimeMillis() - lastFlushTimeMs) >= batchIntervalMs;
     }
 
+    private void recordFlushException(Exception e) {
+        flushFailed = true;
+        flushException =
+                e instanceof JdbcConnectorException
+                        ? e
+                        : new JdbcConnectorException(
+                                CommonErrorCodeDeprecated.FLUSH_DATA_FAILED,
+                                "Writing records to JDBC failed.",
+                                e);
+    }
+
+    protected void sleepBeforeFlushRetry(long sleepMs) throws InterruptedException {
+        Thread.sleep(sleepMs);
+    }
+
+    private List<SQLException> findSqlExceptions(Throwable throwable) {
+        List<SQLException> sqlExceptions = new ArrayList<>();
+        Throwable current = throwable;
+        while (current != null) {
+            if (current instanceof SQLException) {
+                collectSqlExceptionChain((SQLException) current, sqlExceptions);
+            }
+            current = current.getCause();
+        }
+        return sqlExceptions;
+    }
+
+    private void collectSqlExceptionChain(
+            SQLException sqlException, List<SQLException> sqlExceptions) {
+        SQLException current = sqlException;
+        while (current != null) {
+            sqlExceptions.add(current);
+            current = current.getNextException();
+        }
+    }
+
+    private SQLException findNonRetryableDataException(List<SQLException> sqlExceptions) {
+        for (SQLException sqlException : sqlExceptions) {
+            if (isNonRetryableDataException(sqlException)) {
+                return sqlException;
+            }
+        }
+        return null;
+    }
+
+    private boolean isNonRetryableDataException(SQLException sqlException) {
+        if (sqlException instanceof SQLDataException
+                || sqlException instanceof SQLIntegrityConstraintViolationException) {
+            return true;
+        }
+
+        String sqlState = sqlException.getSQLState();
+        if (sqlState != null && (sqlState.startsWith("22") || sqlState.startsWith("23"))) {
+            return true;
+        }
+
+        return isOracleDataException(sqlException);
+    }
+
+    private boolean isOracleDataException(SQLException sqlException) {
+        String message = sqlException.getMessage();
+        if (message == null) {
+            return false;
+        }
+
+        String normalizedMessage = message.toUpperCase(Locale.ROOT);
+        int vendorCode = sqlException.getErrorCode();
+        return (vendorCode == 1 && normalizedMessage.contains("ORA-00001"))
+                || (vendorCode == 12899 && normalizedMessage.contains("ORA-12899"));
+    }
+
     public void updateExecutor(boolean reconnect) throws SQLException, ClassNotFoundException {
         try {
             jdbcStatementExecutor.closeStatements();
@@ -297,26 +474,6 @@ public class JdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>> implem
         return false;
     }
 
-    private List<SQLException> findSqlExceptions(Throwable throwable) {
-        List<SQLException> sqlExceptions = new ArrayList<>();
-        while (throwable != null) {
-            if (throwable instanceof SQLException) {
-                collectSqlExceptionChain((SQLException) throwable, sqlExceptions);
-            }
-            throwable = throwable.getCause();
-        }
-        return sqlExceptions;
-    }
-
-    private void collectSqlExceptionChain(
-            SQLException sqlException, List<SQLException> sqlExceptions) {
-        SQLException current = sqlException;
-        while (current != null) {
-            sqlExceptions.add(current);
-            current = current.getNextException();
-        }
-    }
-
     private boolean isStatementClosed(List<SQLException> sqlExceptions) {
         for (SQLException sqlException : sqlExceptions) {
             if (isStatementClosed(sqlException)) {
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java
index c6e4514e74..8203dbc900 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBuilder.java
@@ -57,6 +57,18 @@ public class JdbcOutputFormatBuilder {
     @NonNull private final TableSchema tableSchema;
     @Nullable private final TableSchema databaseTableSchema;
 
+    private boolean commitOnFlush;
+
+    /**
+     * Commits the connection after every successful batch flush when it uses manual commit. Only
+     * the non-XA writer enables this, and only when checkpointing is disabled, so flushed batches
+     * are not held in one unbounded transaction until close.
+     */
+    public JdbcOutputFormatBuilder commitOnFlush(boolean commitOnFlush) {
+        this.commitOnFlush = commitOnFlush;
+        return this;
+    }
+
     public JdbcOutputFormat build() {
         JdbcOutputFormat.StatementExecutorFactory statementExecutorFactory;
 
@@ -106,7 +118,8 @@ public class JdbcOutputFormatBuilder {
         return new JdbcOutputFormat(
                 connectionProvider,
                 jdbcSinkConfig.getJdbcConnectionConfig(),
-                statementExecutorFactory);
+                statementExecutorFactory,
+                commitOnFlush);
     }
 
     private static JdbcBatchStatementExecutor<SeaTunnelRow> createSimpleBufferedExecutor(
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java
index 91dfc92d67..6ef9112ec3 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferReducedBatchStatementExecutor.java
@@ -45,6 +45,8 @@ public class BufferReducedBatchStatementExecutor
     @NonNull private final LinkedHashMap<SeaTunnelRow, Pair<Boolean, SeaTunnelRow>> buffer =
             new LinkedHashMap<>();
 
+    private boolean flushFailed;
+
     @Override
     public void prepareStatements(Connection connection) throws SQLException {
         upsertExecutor.prepareStatements(connection);
@@ -66,38 +68,44 @@ public class BufferReducedBatchStatementExecutor
 
     @Override
     public void executeBatch() throws SQLException {
-        Boolean preChangeFlag = null;
-        Set<Map.Entry<SeaTunnelRow, Pair<Boolean, SeaTunnelRow>>> entrySet = buffer.entrySet();
-        for (Map.Entry<SeaTunnelRow, Pair<Boolean, SeaTunnelRow>> entry : entrySet) {
-            Boolean currentChangeFlag = entry.getValue().getKey();
-            if (currentChangeFlag) {
-                if (preChangeFlag != null && !preChangeFlag) {
-                    deleteExecutor.executeBatch();
-                }
-                upsertExecutor.addToBatch(entry.getValue().getValue());
-            } else {
-                if (preChangeFlag != null && preChangeFlag) {
-                    upsertExecutor.executeBatch();
+        try {
+            Boolean preChangeFlag = null;
+            Set<Map.Entry<SeaTunnelRow, Pair<Boolean, SeaTunnelRow>>> entrySet = buffer.entrySet();
+            for (Map.Entry<SeaTunnelRow, Pair<Boolean, SeaTunnelRow>> entry : entrySet) {
+                Boolean currentChangeFlag = entry.getValue().getKey();
+                if (currentChangeFlag) {
+                    if (preChangeFlag != null && !preChangeFlag) {
+                        deleteExecutor.executeBatch();
+                    }
+                    upsertExecutor.addToBatch(entry.getValue().getValue());
+                } else {
+                    if (preChangeFlag != null && preChangeFlag) {
+                        upsertExecutor.executeBatch();
+                    }
+                    deleteExecutor.addToBatch(entry.getKey());
                 }
-                deleteExecutor.addToBatch(entry.getKey());
+                preChangeFlag = currentChangeFlag;
             }
-            preChangeFlag = currentChangeFlag;
-        }
 
-        if (preChangeFlag != null) {
-            if (preChangeFlag) {
-                upsertExecutor.executeBatch();
-            } else {
-                deleteExecutor.executeBatch();
+            if (preChangeFlag != null) {
+                if (preChangeFlag) {
+                    upsertExecutor.executeBatch();
+                } else {
+                    deleteExecutor.executeBatch();
+                }
             }
+            buffer.clear();
+            flushFailed = false;
+        } catch (SQLException e) {
+            flushFailed = true;
+            throw e;
         }
-        buffer.clear();
     }
 
     @Override
     public void closeStatements() throws SQLException {
         try {
-            if (!buffer.isEmpty()) {
+            if (!buffer.isEmpty() && !flushFailed) {
                 executeBatch();
             }
         } finally {
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java
index f065841402..e00822df10 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferedBatchStatementExecutor.java
@@ -20,7 +20,6 @@ package org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor;
 import org.apache.seatunnel.api.table.type.SeaTunnelRow;
 
 import lombok.NonNull;
-import lombok.RequiredArgsConstructor;
 
 import java.sql.Connection;
 import java.sql.SQLException;
@@ -28,11 +27,18 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.function.Function;
 
-@RequiredArgsConstructor
 public class BufferedBatchStatementExecutor implements JdbcBatchStatementExecutor<SeaTunnelRow> {
     @NonNull private final JdbcBatchStatementExecutor<SeaTunnelRow> statementExecutor;
     @NonNull private final Function<SeaTunnelRow, SeaTunnelRow> valueTransform;
     @NonNull private final List<SeaTunnelRow> buffer = new ArrayList<>();
+    private boolean flushFailed;
+
+    public BufferedBatchStatementExecutor(
+            @NonNull JdbcBatchStatementExecutor<SeaTunnelRow> statementExecutor,
+            @NonNull Function<SeaTunnelRow, SeaTunnelRow> valueTransform) {
+        this.statementExecutor = statementExecutor;
+        this.valueTransform = valueTransform;
+    }
 
     @Override
     public void prepareStatements(Connection connection) throws SQLException {
@@ -47,11 +53,17 @@ public class BufferedBatchStatementExecutor implements JdbcBatchStatementExecuto
     @Override
     public void executeBatch() throws SQLException {
         if (!buffer.isEmpty()) {
-            for (SeaTunnelRow row : buffer) {
-                statementExecutor.addToBatch(row);
+            try {
+                for (SeaTunnelRow row : buffer) {
+                    statementExecutor.addToBatch(row);
+                }
+                statementExecutor.executeBatch();
+                buffer.clear();
+                flushFailed = false;
+            } catch (SQLException e) {
+                flushFailed = true;
+                throw e;
             }
-            statementExecutor.executeBatch();
-            buffer.clear();
         }
     }
 
@@ -64,7 +76,7 @@ public class BufferedBatchStatementExecutor implements JdbcBatchStatementExecuto
     @Override
     public void closeStatements() throws SQLException {
         try {
-            if (!buffer.isEmpty()) {
+            if (!buffer.isEmpty() && !flushFailed) {
                 executeBatch();
             }
         } finally {
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
index fa8a241813..d552fd19b5 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/AbstractJdbcSinkWriter.java
@@ -57,6 +57,14 @@ public abstract class AbstractJdbcSinkWriter<ResourceT>
     protected JdbcConnectionProvider connectionProvider;
     protected JdbcSinkConfig jdbcSinkConfig;
     protected JdbcOutputFormat<SeaTunnelRow, JdbcBatchStatementExecutor<SeaTunnelRow>> outputFormat;
+
+    /**
+     * Whether every successful batch flush should commit the connection when it uses manual commit.
+     * Only the non-XA writer sets this to true, and only when checkpointing is disabled, so rebuilt
+     * output formats keep the same commit boundary after schema changes.
+     */
+    protected boolean commitOnFlush;
+
     protected TableSchemaChangeEventDispatcher tableSchemaChanger =
             new TableSchemaChangeEventDispatcher();
 
@@ -101,6 +109,7 @@ public abstract class AbstractJdbcSinkWriter<ResourceT>
                                 jdbcSinkConfig,
                                 tableSchema,
                                 databaseTableSchema)
+                        .commitOnFlush(commitOnFlush)
                         .build();
         this.outputFormat.open();
     }
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java
index b4d56f3a66..f44509bd6f 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSink.java
@@ -157,7 +157,8 @@ public class JdbcSink
                             jdbcSinkConfig,
                             tableSchema,
                             getDatabaseTableSchema().orElse(null),
-                            primaryKeyIndex);
+                            primaryKeyIndex,
+                            jobContext == null || jobContext.isEnableCheckpoint());
         }
         return sinkWriter;
     }
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
index 36cad4e525..8cbe3a6a24 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriter.java
@@ -96,12 +96,39 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
             TableSchema tableSchema,
             TableSchema databaseTableSchema,
             Integer primaryKeyIndex) {
+        this(
+                sinkTablePath,
+                context,
+                dialect,
+                jdbcSinkConfig,
+                tableSchema,
+                databaseTableSchema,
+                primaryKeyIndex,
+                true);
+    }
+
+    public JdbcSinkWriter(
+            TablePath sinkTablePath,
+            SinkWriter.Context context,
+            JdbcDialect dialect,
+            JdbcSinkConfig jdbcSinkConfig,
+            TableSchema tableSchema,
+            TableSchema databaseTableSchema,
+            Integer primaryKeyIndex,
+            boolean checkpointEnabled) {
         this.sinkTablePath = sinkTablePath;
         this.dialect = dialect;
         this.tableSchema = tableSchema;
         this.databaseTableSchema = databaseTableSchema;
         this.jdbcSinkConfig = jdbcSinkConfig;
         this.primaryKeyIndex = primaryKeyIndex;
+        // Without checkpointing there is no prepareCommit boundary to commit manual-commit
+        // connections (for example Oracle, which is forced to manual commit above), so every
+        // successful batch flush must carry its own commit or flushed rows stay in one unbounded
+        // transaction until close. With checkpointing enabled the commit boundary stays at
+        // prepareCommit to keep the existing checkpoint semantics.
+        this.commitOnFlush = !checkpointEnabled;
+        this.connectionProvider = dialect.getJdbcConnectionProvider(resolveSinkConnectionConfig());
         this.rowErrorCollector =
                 context == null ? Optional.empty() : context.getRowErrorCollector();
         this.batchSize = jdbcSinkConfig.getJdbcConnectionConfig().getBatchSize();
@@ -112,8 +139,6 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
                 context.enableDeferredTerminalWriteOutcomes();
             }
         }
-        this.connectionProvider =
-                dialect.getJdbcConnectionProvider(jdbcSinkConfig.getJdbcConnectionConfig());
         this.outputFormat =
                 new JdbcOutputFormatBuilder(
                                 dialect,
@@ -121,6 +146,7 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
                                 jdbcSinkConfig,
                                 tableSchema,
                                 databaseTableSchema)
+                        .commitOnFlush(commitOnFlush)
                         .build();
         configureOutputFormatForRowErrorHandling();
         if (context != null) {
@@ -150,12 +176,69 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
         if (jdbcSinkConfig.getJdbcConnectionConfig().getPassword().isPresent()) {
             ds.setPassword(jdbcSinkConfig.getJdbcConnectionConfig().getPassword().get());
         }
-        ds.setAutoCommit(jdbcSinkConfig.getJdbcConnectionConfig().isAutoCommit());
+        ds.setAutoCommit(resolveSinkAutoCommit());
         applyConnectionValidation(ds, jdbcSinkConfig.getJdbcConnectionConfig());
         jdbcSinkConfig.getJdbcConnectionConfig().getProperties().forEach(ds::addDataSourceProperty);
         return new JdbcMultiTableResourceManager(new ConnectionPoolManager(ds));
     }
 
+    private boolean resolveSinkAutoCommit() {
+        // Oracle may partially commit a failed JDBC batch when auto-commit is enabled. Keep the
+        // batch atomic there so the original data error is not masked by a later duplicate-key
+        // error.
+        if (DatabaseIdentifier.ORACLE.equals(dialect.dialectName())) {
+            return false;
+        }
+        return jdbcSinkConfig.getJdbcConnectionConfig().isAutoCommit();
+    }
+
+    private JdbcConnectionConfig resolveSinkConnectionConfig() {
+        JdbcConnectionConfig connectionConfig = jdbcSinkConfig.getJdbcConnectionConfig();
+        if (!DatabaseIdentifier.ORACLE.equals(dialect.dialectName())) {
+            return connectionConfig;
+        }
+
+        return copyConnectionConfig(connectionConfig, false);
+    }
+
+    private JdbcConnectionConfig copyConnectionConfig(
+            JdbcConnectionConfig connectionConfig, boolean autoCommit) {
+        JdbcConnectionConfig.Builder builder =
+                JdbcConnectionConfig.builder()
+                        .url(connectionConfig.getUrl())
+                        .driverName(connectionConfig.getDriverName())
+                        .compatibleMode(connectionConfig.getCompatibleMode())
+                        .connectionCheckTimeoutSeconds(
+                                connectionConfig.getConnectionCheckTimeoutSeconds())
+                        .maxRetries(connectionConfig.getMaxRetries())
+                        .query(connectionConfig.getQuery())
+                        .autoCommit(autoCommit)
+                        .batchSize(connectionConfig.getBatchSize())
+                        .batchIntervalMs(connectionConfig.getBatchIntervalMs())
+                        .isExactlyOnce(connectionConfig.isExactlyOnce())
+                        .xaDataSourceClassName(connectionConfig.getXaDataSourceClassName())
+                        .decimalTypeNarrowing(connectionConfig.isDecimalTypeNarrowing())
+                        .intTypeNarrowing(connectionConfig.isIntTypeNarrowing())
+                        .handleBlobAsString(connectionConfig.isHandleBlobAsString())
+                        .maxCommitAttempts(connectionConfig.getMaxCommitAttempts())
+                        .transactionTimeoutSec(
+                                connectionConfig.getTransactionTimeoutSec().orElse(-1))
+                        .socketTimeoutMs(connectionConfig.getSocketTimeoutMs())
+                        .connectTimeoutMs(connectionConfig.getConnectTimeoutMs())
+                        .properties(connectionConfig.getProperties())
+                        .useKerberos(connectionConfig.isUseKerberos())
+                        .kerberosPrincipal(connectionConfig.getKerberosPrincipal())
+                        .kerberosKeytabPath(connectionConfig.getKerberosKeytabPath())
+                        .krb5Path(connectionConfig.getKrb5Path())
+                        .dialect(connectionConfig.getDialect())
+                        .region(connectionConfig.getRegion())
+                        .accessKeyId(connectionConfig.getAccessKeyId())
+                        .secretAccessKey(connectionConfig.getSecretAccessKey());
+        connectionConfig.getUsername().ifPresent(builder::username);
+        connectionConfig.getPassword().ifPresent(builder::password);
+        return builder.build();
+    }
+
     /**
      * Configures pool-level validation for JDBC drivers that cannot pass Hikari's default
      * Connection.isValid(timeout) probe.
@@ -189,6 +272,7 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
                                 jdbcSinkConfig,
                                 tableSchema,
                                 databaseTableSchema)
+                        .commitOnFlush(commitOnFlush)
                         .build();
         configureOutputFormatForRowErrorHandling();
     }
@@ -251,6 +335,10 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
     }
 
     private boolean isRowLevelDataError(Throwable t) {
+        // A failed commit has an unknown durable outcome, even for SQLState 22/23.
+        if (outputFormat.hasCommitFailed()) {
+            return false;
+        }
         // Only treat SQL data/constraint violations as row-level errors.
         Throwable cause = t;
         while (cause != null) {
@@ -314,15 +402,23 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
         }
 
         tryOpen();
-        outputFormat.checkFlushException();
-        outputFormat.flush();
         try {
+            outputFormat.checkFlushException();
+            outputFormat.flush();
             commitIfNeeded();
         } catch (SQLException e) {
+            rollbackIfNeeded("prepare commit");
             throw new JdbcConnectorException(
                     JdbcConnectorErrorCode.TRANSACTION_OPERATION_FAILED,
                     "commit failed," + e.getMessage(),
                     e);
+        } catch (IOException e) {
+            rollbackIfNeeded("prepare commit");
+            throw e;
+        } catch (Exception e) {
+            rollbackIfNeeded("prepare commit");
+            throw new JdbcConnectorException(
+                    CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, "prepare commit failed", e);
         }
         return Optional.empty();
     }
@@ -353,13 +449,12 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
         }
 
         tryOpen();
-        outputFormat.flush();
         try {
-            Connection connection = connectionProvider.getConnection();
-            if (!connection.getAutoCommit()) {
-                connection.commit();
-            }
-        } catch (SQLException e) {
+            outputFormat.checkFlushException();
+            outputFormat.flush();
+            commitIfNeeded();
+        } catch (Exception e) {
+            rollbackIfNeeded("close");
             throw new JdbcConnectorException(
                     CommonErrorCodeDeprecated.WRITER_OPERATION_FAILED,
                     "unable to close JDBC sink write",
@@ -382,7 +477,8 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
     }
 
     private boolean markSuccessfulAutoFlushBoundaryIfNeeded() throws IOException {
-        if (jdbcSinkConfig.getJdbcConnectionConfig().isAutoCommit()) {
+        if (commitOnFlush || resolveSinkAutoCommit()) {
+            lastSuccessfulBatchSavepoint = null;
             return true;
         }
         if (!supportsSavepoints()) {
@@ -491,6 +587,7 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
         if (failure != null) {
             throw failure;
         }
+        outputFormat.resetAfterRowError();
     }
 
     private void rollbackIfNeeded() throws SQLException {
@@ -564,15 +661,34 @@ public class JdbcSinkWriter extends AbstractJdbcSinkWriter<ConnectionPoolManager
         }
 
         tryOpen();
-        outputFormat.checkFlushException();
-        outputFormat.flush();
         try {
+            outputFormat.checkFlushException();
+            outputFormat.flush();
             commitIfNeeded();
         } catch (SQLException e) {
+            rollbackIfNeeded("timer flush");
             throw new JdbcConnectorException(
                     JdbcConnectorErrorCode.TRANSACTION_OPERATION_FAILED,
                     "timer flush commit failed: " + e.getMessage(),
                     e);
+        } catch (IOException e) {
+            rollbackIfNeeded("timer flush");
+            throw e;
+        } catch (Exception e) {
+            rollbackIfNeeded("timer flush");
+            throw new JdbcConnectorException(
+                    CommonErrorCodeDeprecated.FLUSH_DATA_FAILED, "timer flush failed", e);
+        }
+    }
+
+    private void rollbackIfNeeded(String phase) {
+        try {
+            Connection connection = connectionProvider.getConnection();
+            if (connection != null && !connection.getAutoCommit()) {
+                connection.rollback();
+            }
+        } catch (SQLException rollbackException) {
+            log.warn("Rollback jdbc sink writer failed during {}.", phase, rollbackException);
         }
     }
 }
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBatchCommitTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBatchCommitTest.java
new file mode 100644
index 0000000000..ce784306d0
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatBatchCommitTest.java
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.jdbc.internal;
+
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcConnectionConfig;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcConnectionProvider;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.JdbcBatchStatementExecutor;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+/** Tests the commit boundary of batch-size-triggered flushes in {@link JdbcOutputFormat}. */
+class JdbcOutputFormatBatchCommitTest {
+
+    @Test
+    void testInternalBatchFlushCommitsWhenCommitOnFlushEnabled() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        CountingExecutor executor = new CountingExecutor();
+        JdbcOutputFormat<SeaTunnelRow, CountingExecutor> outputFormat =
+                new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor, true);
+        outputFormat.open();
+
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+        Mockito.verify(connection, Mockito.never()).commit();
+
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"BB"}));
+
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.times(1)).commit();
+    }
+
+    @Test
+    void testInternalBatchFlushSkipsCommitWhenCommitOnFlushDisabled() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        CountingExecutor executor = new CountingExecutor();
+        JdbcOutputFormat<SeaTunnelRow, CountingExecutor> outputFormat =
+                new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor, false);
+        outputFormat.open();
+
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"BB"}));
+
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.never()).commit();
+    }
+
+    @Test
+    void testInternalBatchFlushSkipsCommitForAutoCommitConnection() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(true);
+
+        CountingExecutor executor = new CountingExecutor();
+        JdbcOutputFormat<SeaTunnelRow, CountingExecutor> outputFormat =
+                new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor, true);
+        outputFormat.open();
+
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"BB"}));
+
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.never()).commit();
+    }
+
+    @Test
+    void testCommitFailureAfterBatchFlushShouldNotReconnectAndRetryEmptyBatch() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+        Mockito.doThrow(new SQLException("commit failed", "08006")).when(connection).commit();
+
+        CountingExecutor executor = new CountingExecutor();
+        JdbcOutputFormat<SeaTunnelRow, CountingExecutor> outputFormat =
+                new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor, true);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, outputFormat::flush);
+
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.times(1)).commit();
+        Mockito.verify(provider, Mockito.never()).reestablishConnection();
+    }
+
+    @Test
+    void testRowErrorRecoveryCannotClearAmbiguousCommitFailure() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+        Mockito.doThrow(new SQLException("deferred constraint failed", "23000"))
+                .when(connection)
+                .commit();
+        CountingExecutor executor = new CountingExecutor();
+        JdbcOutputFormat<SeaTunnelRow, CountingExecutor> format =
+                new JdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor, true);
+        format.setFailFastOnRowLevelSqlState(true);
+        format.open();
+        format.writeRecord(new SeaTunnelRow(new Object[] {"row"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, format::flush);
+        Assertions.assertTrue(format.hasCommitFailed());
+        format.clearBatchSilently();
+        format.resetAfterRowError();
+        Assertions.assertThrows(JdbcConnectorException.class, format::checkFlushException);
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(provider, Mockito.never()).reestablishConnection();
+    }
+
+    private static JdbcConnectionConfig buildConnectionConfig() {
+        return JdbcConnectionConfig.builder()
+                .url("jdbc:test")
+                .batchSize(2)
+                .batchIntervalMs(0)
+                .build();
+    }
+
+    private static class CountingExecutor implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+        private int executeBatchCalls;
+
+        @Override
+        public void prepareStatements(Connection connection) {}
+
+        @Override
+        public void addToBatch(SeaTunnelRow record) {}
+
+        @Override
+        public void executeBatch() {
+            executeBatchCalls++;
+        }
+
+        @Override
+        public void closeStatements() {}
+    }
+}
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectSafetyTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectSafetyTest.java
new file mode 100644
index 0000000000..c1727286dc
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatReconnectSafetyTest.java
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.jdbc.internal;
+
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcConnectionConfig;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorException;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcConnectionProvider;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.JdbcBatchStatementExecutor;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+class JdbcOutputFormatReconnectSafetyTest {
+
+    @Test
+    void testFlushRetryShouldFailFastWhenIntegrityConstraintViolation() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(provider.isConnectionValid()).thenReturn(true);
+
+        TestNonRetryableDataErrorExecutor executor =
+                new TestNonRetryableDataErrorExecutor(
+                        new SQLException("ORA-00001: unique constraint violated", "23000", 1));
+
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TestNonRetryableDataErrorExecutor> outputFormat =
+                new NoSleepJdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, outputFormat::flush);
+
+        Assertions.assertEquals(1, executor.prepareStatementsCalls);
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Assertions.assertEquals(0, executor.closeStatementsCalls);
+        Mockito.verify(provider, Mockito.never()).reestablishConnection();
+    }
+
+    @Test
+    void testFlushRetryShouldFailFastWhenOracleValueTooLarge() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(provider.isConnectionValid()).thenReturn(true);
+
+        TestNonRetryableDataErrorExecutor executor =
+                new TestNonRetryableDataErrorExecutor(
+                        new SQLException("ORA-12899: value too large for column", "72000", 12899));
+
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TestNonRetryableDataErrorExecutor> outputFormat =
+                new NoSleepJdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, outputFormat::flush);
+
+        Assertions.assertEquals(1, executor.prepareStatementsCalls);
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Assertions.assertEquals(0, executor.closeStatementsCalls);
+        Mockito.verify(provider, Mockito.never()).reestablishConnection();
+    }
+
+    @Test
+    void testCloseShouldNotFlushAgainAfterFlushFailure() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(provider.isConnectionValid()).thenReturn(true);
+
+        TestNonRetryableDataErrorExecutor executor =
+                new TestNonRetryableDataErrorExecutor(
+                        new SQLException("ORA-12899: value too large for column", "72000", 12899));
+
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TestNonRetryableDataErrorExecutor> outputFormat =
+                new NoSleepJdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, outputFormat::flush);
+        Assertions.assertThrows(JdbcConnectorException.class, outputFormat::close);
+
+        Assertions.assertEquals(1, executor.prepareStatementsCalls);
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Assertions.assertEquals(1, executor.closeStatementsCalls);
+    }
+
+    @Test
+    void testFlushRetryShouldNotTreatGenericVendorCodeOneAsOracleDataError() throws Exception {
+        JdbcConnectionProvider provider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(provider.getOrEstablishConnection()).thenReturn(connection);
+        Mockito.when(provider.getConnection()).thenReturn(connection);
+        Mockito.when(provider.isConnectionValid()).thenReturn(true);
+
+        TestNonRetryableDataErrorExecutor executor =
+                new TestNonRetryableDataErrorExecutor(
+                        new SQLException("generic driver failure", "HY000", 1));
+
+        NoSleepJdbcOutputFormat<SeaTunnelRow, TestNonRetryableDataErrorExecutor> outputFormat =
+                new NoSleepJdbcOutputFormat<>(provider, buildConnectionConfig(), () -> executor);
+        outputFormat.open();
+        outputFormat.writeRecord(new SeaTunnelRow(new Object[] {"AA"}));
+
+        Assertions.assertThrows(JdbcConnectorException.class, outputFormat::flush);
+
+        Assertions.assertEquals(1, executor.prepareStatementsCalls);
+        Assertions.assertEquals(3, executor.executeBatchCalls);
+        Assertions.assertEquals(0, executor.closeStatementsCalls);
+        Mockito.verify(provider, Mockito.never()).reestablishConnection();
+    }
+
+    private static JdbcConnectionConfig buildConnectionConfig() {
+        return JdbcConnectionConfig.builder()
+                .url("jdbc:test")
+                .batchSize(100)
+                .batchIntervalMs(0)
+                .maxRetries(2)
+                .build();
+    }
+
+    private static class NoSleepJdbcOutputFormat<I, E extends JdbcBatchStatementExecutor<I>>
+            extends JdbcOutputFormat<I, E> {
+        private NoSleepJdbcOutputFormat(
+                JdbcConnectionProvider connectionProvider,
+                JdbcConnectionConfig jdbcConnectionConfig,
+                StatementExecutorFactory<E> statementExecutorFactory) {
+            super(connectionProvider, jdbcConnectionConfig, statementExecutorFactory);
+        }
+
+        @Override
+        protected void sleepBeforeFlushRetry(long sleepMs) throws InterruptedException {}
+    }
+
+    private static class TestNonRetryableDataErrorExecutor
+            implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+        private final SQLException flushFailure;
+        private int prepareStatementsCalls;
+        private int executeBatchCalls;
+        private int closeStatementsCalls;
+
+        private TestNonRetryableDataErrorExecutor(SQLException flushFailure) {
+            this.flushFailure = flushFailure;
+        }
+
+        @Override
+        public void prepareStatements(Connection connection) {
+            prepareStatementsCalls++;
+        }
+
+        @Override
+        public void addToBatch(SeaTunnelRow record) {}
+
+        @Override
+        public void executeBatch() throws SQLException {
+            executeBatchCalls++;
+            throw flushFailure;
+        }
+
+        @Override
+        public void closeStatements() {
+            closeStatementsCalls++;
+        }
+    }
+}
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatTest.java
index fd397eb29e..97a0d548cc 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatTest.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/JdbcOutputFormatTest.java
@@ -91,7 +91,7 @@ public class JdbcOutputFormatTest {
     }
 
     @Test
-    public void testRowLevelSqlStateStillRetriesByDefault() throws Exception {
+    public void testRowLevelSqlStateFailsFastOnValidConnection() throws Exception {
         JdbcConnectionProvider connectionProvider = mock(JdbcConnectionProvider.class);
         Connection connection = mock(Connection.class);
         RowLevelSQLExceptionExecutor executor = new RowLevelSQLExceptionExecutor();
@@ -108,7 +108,7 @@ public class JdbcOutputFormatTest {
 
         Assertions.assertThrows(
                 JdbcConnectorException.class, () -> outputFormat.writeRecord("row-1"));
-        Assertions.assertEquals(2, executor.executeBatchCount);
+        Assertions.assertEquals(1, executor.executeBatchCount);
     }
 
     @Test
@@ -132,6 +132,32 @@ public class JdbcOutputFormatTest {
         Assertions.assertEquals(1, executor.executeBatchCount);
     }
 
+    @Test
+    public void testDiscardedRowErrorBatchAllowsNextWrite() throws Exception {
+        JdbcConnectionProvider provider = mock(JdbcConnectionProvider.class);
+        CountingExecutor executor =
+                new CountingExecutor() {
+                    @Override
+                    public void executeBatch() throws SQLException {
+                        if (++executeBatchCount == 1) {
+                            throw new SQLException("data too long", "22001");
+                        }
+                    }
+                };
+        JdbcOutputFormat<String, CountingExecutor> format =
+                new JdbcOutputFormat<>(
+                        provider,
+                        JdbcConnectionConfig.builder().batchSize(1).build(),
+                        () -> executor);
+        format.setFailFastOnRowLevelSqlState(true);
+        format.open();
+        Assertions.assertThrows(JdbcConnectorException.class, () -> format.writeRecord("bad"));
+        format.clearBatchSilently();
+        format.resetAfterRowError();
+        Assertions.assertDoesNotThrow(() -> format.writeRecord("good"));
+        Assertions.assertEquals(2, executor.executeBatchCount);
+    }
+
     private static void setLastFlushTimeMs(JdbcOutputFormat<?, ?> outputFormat, long value)
             throws Exception {
         Field field = JdbcOutputFormat.class.getDeclaredField("lastFlushTimeMs");
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferExecutorTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferExecutorTest.java
index 1ca5c5f6b4..21bbb93b98 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferExecutorTest.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/executor/BufferExecutorTest.java
@@ -43,17 +43,17 @@ public abstract class BufferExecutorTest {
         SQLException exception =
                 Assertions.assertThrows(SQLException.class, executor::executeBatch);
         Assertions.assertEquals("test", exception.getMessage());
-        // the main point of this test is to check if the buffer is cleared after closeStatements
-        // and prepareStatements when executeBatch failed
-        Assertions.assertThrows(SQLException.class, executor::closeStatements);
+        // closeStatements should not flush a batch that already failed, but the local buffer must
+        // stay available for a later recovery path.
+        Assertions.assertDoesNotThrow(executor::closeStatements);
         executor.prepareStatements(new TestConnection());
         SQLException exception2 =
                 Assertions.assertThrows(SQLException.class, executor::executeBatch);
         Assertions.assertEquals("test", exception2.getMessage());
 
-        // three times of addToBatch, 1. executeBatch, 2. closeStatements, 3. executeBatch
-        Assertions.assertEquals(3, recorder.size());
+        // two times of addToBatch, 1. executeBatch, 2. executeBatch after recovery
+        Assertions.assertEquals(2, recorder.size());
         // same row to executeBatch
-        Assertions.assertEquals(recorder.get(0), recorder.get(2));
+        Assertions.assertEquals(recorder.get(0), recorder.get(1));
     }
 }
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterSharedPhysicalTableSchemaChangeTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterSharedPhysicalTableSchemaChangeTest.java
index 380c958d62..10ae21af82 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterSharedPhysicalTableSchemaChangeTest.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterSharedPhysicalTableSchemaChangeTest.java
@@ -96,7 +96,8 @@ class JdbcSinkWriterSharedPhysicalTableSchemaChangeTest {
                         sinkConfig,
                         schemaBeforeDrop,
                         schemaBeforeDrop,
-                        null);
+                        null,
+                        true);
         JdbcSinkWriter writerB =
                 new JdbcSinkWriter(
                         SHARED_SINK_TABLE,
@@ -105,7 +106,8 @@ class JdbcSinkWriterSharedPhysicalTableSchemaChangeTest {
                         sinkConfig,
                         schemaBeforeDrop,
                         schemaBeforeDrop,
-                        null);
+                        null,
+                        true);
 
         Map<SinkIdentifier, SinkWriter<SeaTunnelRow, ?, ?>> writers = new LinkedHashMap<>();
         writers.put(SinkIdentifier.of(SOURCE_A, 0), writerA);
diff --git a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterTest.java b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterTest.java
index 8cf06b4599..9665880928 100644
--- a/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterTest.java
+++ b/seatunnel-connectors-v2/connector-jdbc/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/sink/JdbcSinkWriterTest.java
@@ -21,6 +21,7 @@ import org.apache.seatunnel.shade.com.zaxxer.hikari.HikariDataSource;
 
 import org.apache.seatunnel.api.common.error.RowErrorCollector;
 import org.apache.seatunnel.api.common.error.RowErrorEvent;
+import org.apache.seatunnel.api.sink.MultiTableResourceManager;
 import org.apache.seatunnel.api.sink.SinkWriter;
 import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
 import org.apache.seatunnel.api.table.catalog.TablePath;
@@ -34,22 +35,32 @@ import org.apache.seatunnel.connectors.seatunnel.jdbc.exception.JdbcConnectorExc
 import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.JdbcOutputFormat;
 import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcConnectionProvider;
 import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.connection.JdbcConnectionValidationUtils;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.converter.JdbcRowConverter;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.DatabaseIdentifier;
 import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.JdbcDialect;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.executor.JdbcBatchStatementExecutor;
 
 import org.junit.jupiter.api.Assertions;
 import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 import java.sql.Connection;
 import java.sql.DatabaseMetaData;
+import java.sql.Driver;
+import java.sql.DriverPropertyInfo;
 import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
 import java.sql.Savepoint;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Optional;
+import java.util.Properties;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.logging.Logger;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
@@ -158,6 +169,33 @@ class JdbcSinkWriterTest {
         Assertions.assertNull(getLastSuccessfulBatchSavepoint(writer));
     }
 
+    @Test
+    void testCommittedAutoFlushDoesNotCreateSavepoint() throws Exception {
+        AtomicInteger successCount = new AtomicInteger();
+        WriterFixture fixture = createWriterFixture(false, successCount);
+        fixture.writer.commitOnFlush = true;
+        List<SeaTunnelRow> pendingRows = new ArrayList<>();
+        pendingRows.add(new SeaTunnelRow(new Object[] {1}));
+        setPendingRows(fixture.writer, pendingRows);
+        invokeReportAndClearPendingRowsIfCommitted(fixture.writer, true);
+        Assertions.assertEquals(1, successCount.get());
+        Assertions.assertTrue(getPendingRows(fixture.writer).isEmpty());
+        verify(fixture.connection, never()).setSavepoint();
+    }
+
+    @Test
+    void testCommitFailureIsNotClassifiedAsRowError() throws Exception {
+        JdbcSinkWriter writer = createWriterWithRowErrorCollector(false);
+        JdbcOutputFormat outputFormat = mock(JdbcOutputFormat.class);
+        when(outputFormat.hasCommitFailed()).thenReturn(true);
+        setOutputFormat(writer, outputFormat);
+        Assertions.assertEquals(
+                org.apache.seatunnel.api.common.error.RowErrorClassification.SYSTEM_ERROR,
+                writer.classifyRowError(
+                        new SQLException("commit failed", "23000"),
+                        new SeaTunnelRow(new Object[] {1})));
+    }
+
     @Test
     void testNonCollectorWriteDoesNotClearBatchOnRowLevelError() throws Exception {
         JdbcSinkWriter writer = createWriterWithoutRowErrorCollector();
@@ -214,6 +252,298 @@ class JdbcSinkWriterTest {
         dataSource.close();
     }
 
+    /** Oracle sink ignores user auto_commit=true at runtime to keep failed batches atomic. */
+    @Test
+    void testOracleSinkResourceManagerUsesManualCommit() {
+        JdbcDialect dialect = Mockito.mock(JdbcDialect.class);
+        Mockito.when(dialect.dialectName()).thenReturn(DatabaseIdentifier.ORACLE);
+        Mockito.when(dialect.getJdbcConnectionProvider(Mockito.any()))
+                .thenReturn(Mockito.mock(JdbcConnectionProvider.class));
+        Mockito.when(dialect.getRowConverter()).thenReturn(Mockito.mock(JdbcRowConverter.class));
+
+        JdbcConnectionConfig jdbcConnectionConfig =
+                JdbcConnectionConfig.builder()
+                        .driverName(DummyDriver.class.getName())
+                        .url("jdbc:dummy:oracle-auto-commit")
+                        .autoCommit(true)
+                        .build();
+        JdbcSinkConfig jdbcSinkConfig =
+                JdbcSinkConfig.builder()
+                        .jdbcConnectionConfig(jdbcConnectionConfig)
+                        .simpleSql("INSERT INTO TEST_TABLE(ID) VALUES (?)")
+                        .build();
+        TableSchema tableSchema =
+                TableSchema.builder()
+                        .column(PhysicalColumn.of("ID", BasicType.INT_TYPE, 22L, false, null, "ID"))
+                        .build();
+        JdbcSinkWriter writer =
+                new JdbcSinkWriter(
+                        null,
+                        Mockito.mock(SinkWriter.Context.class),
+                        dialect,
+                        jdbcSinkConfig,
+                        tableSchema,
+                        tableSchema,
+                        null,
+                        true);
+
+        MultiTableResourceManager<ConnectionPoolManager> resourceManager =
+                writer.initMultiTableResourceManager(1, 1);
+
+        try {
+            ConnectionPoolManager connectionPoolManager =
+                    resourceManager.getSharedResource().orElseThrow(AssertionError::new);
+            Assertions.assertFalse(connectionPoolManager.getConnectionPool().isAutoCommit());
+        } finally {
+            resourceManager.close();
+        }
+    }
+
+    /** Oracle single-table sink also ignores user auto_commit=true at runtime. */
+    @Test
+    void testOracleSinkSingleTableProviderUsesManualCommit() {
+        JdbcDialect dialect = Mockito.mock(JdbcDialect.class);
+        JdbcConnectionProvider connectionProvider = Mockito.mock(JdbcConnectionProvider.class);
+        ArgumentCaptor<JdbcConnectionConfig> configCaptor =
+                ArgumentCaptor.forClass(JdbcConnectionConfig.class);
+        Mockito.when(dialect.dialectName()).thenReturn(DatabaseIdentifier.ORACLE);
+        Mockito.when(dialect.getJdbcConnectionProvider(configCaptor.capture()))
+                .thenReturn(connectionProvider);
+        Mockito.when(dialect.getRowConverter()).thenReturn(Mockito.mock(JdbcRowConverter.class));
+
+        JdbcConnectionConfig jdbcConnectionConfig =
+                JdbcConnectionConfig.builder()
+                        .driverName(DummyDriver.class.getName())
+                        .url("jdbc:dummy:oracle-single-table")
+                        .autoCommit(true)
+                        .build();
+        JdbcSinkConfig jdbcSinkConfig = buildJdbcSinkConfig(jdbcConnectionConfig);
+        TableSchema tableSchema = buildTableSchema();
+
+        new JdbcSinkWriter(
+                null,
+                Mockito.mock(SinkWriter.Context.class),
+                dialect,
+                jdbcSinkConfig,
+                tableSchema,
+                tableSchema,
+                null,
+                true);
+
+        Assertions.assertTrue(jdbcConnectionConfig.isAutoCommit());
+        Assertions.assertFalse(configCaptor.getValue().isAutoCommit());
+    }
+
+    /** Close must rollback, not commit, when a previous flush failure is already recorded. */
+    @Test
+    void testCloseShouldNotCommitAfterKnownFlushFailure() throws Exception {
+        JdbcDialect dialect = Mockito.mock(JdbcDialect.class);
+        JdbcConnectionProvider connectionProvider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(dialect.dialectName()).thenReturn(DatabaseIdentifier.POSTGRESQL);
+        Mockito.when(dialect.getJdbcConnectionProvider(Mockito.any()))
+                .thenReturn(connectionProvider);
+        Mockito.when(dialect.getRowConverter()).thenReturn(Mockito.mock(JdbcRowConverter.class));
+        Mockito.when(connectionProvider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        JdbcSinkWriter writer =
+                new JdbcSinkWriter(
+                        null,
+                        Mockito.mock(SinkWriter.Context.class),
+                        dialect,
+                        buildJdbcSinkConfig(
+                                JdbcConnectionConfig.builder()
+                                        .driverName(DummyDriver.class.getName())
+                                        .url("jdbc:dummy:close-flush-failure")
+                                        .autoCommit(false)
+                                        .build()),
+                        buildTableSchema(),
+                        buildTableSchema(),
+                        null,
+                        true);
+        JdbcOutputFormat<SeaTunnelRow, JdbcBatchStatementExecutor<SeaTunnelRow>> outputFormat =
+                Mockito.mock(JdbcOutputFormat.class);
+        writer.outputFormat = outputFormat;
+        writer.isOpen = true;
+        Mockito.doThrow(new RuntimeException("previous flush failed"))
+                .when(outputFormat)
+                .checkFlushException();
+
+        Assertions.assertThrows(JdbcConnectorException.class, writer::close);
+
+        Mockito.verify(outputFormat, Mockito.never()).flush();
+        Mockito.verify(connection, Mockito.never()).commit();
+        Mockito.verify(connection).rollback();
+        Mockito.verify(outputFormat).close();
+    }
+
+    /**
+     * A batch_size-triggered flush must carry its own commit when checkpointing (and the engine
+     * timer flush) is disabled, or a manual-commit connection such as Oracle would keep every
+     * flushed batch in one unbounded transaction until close.
+     */
+    @Test
+    void testBatchSizeFlushCommitsWhenCheckpointDisabled() throws Exception {
+        JdbcDialect dialect = Mockito.mock(JdbcDialect.class);
+        JdbcConnectionProvider connectionProvider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(dialect.dialectName()).thenReturn(DatabaseIdentifier.ORACLE);
+        Mockito.when(dialect.getJdbcConnectionProvider(Mockito.any()))
+                .thenReturn(connectionProvider);
+        Mockito.when(dialect.getRowConverter()).thenReturn(Mockito.mock(JdbcRowConverter.class));
+        Mockito.when(connectionProvider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        JdbcConnectionConfig connectionConfig =
+                JdbcConnectionConfig.builder()
+                        .driverName(DummyDriver.class.getName())
+                        .url("jdbc:dummy:batch-flush-commit")
+                        .autoCommit(true)
+                        .batchSize(2)
+                        .batchIntervalMs(0)
+                        .build();
+        JdbcSinkWriter writer =
+                new JdbcSinkWriter(
+                        null,
+                        Mockito.mock(SinkWriter.Context.class),
+                        dialect,
+                        buildJdbcSinkConfig(connectionConfig),
+                        buildTableSchema(),
+                        buildTableSchema(),
+                        null,
+                        false);
+        Assertions.assertTrue(writer.commitOnFlush);
+
+        CountingExecutor executor = new CountingExecutor();
+        writer.outputFormat =
+                new JdbcOutputFormat<>(connectionProvider, connectionConfig, () -> executor, true);
+
+        // First record stays buffered: no flush and no commit yet.
+        writer.write(new SeaTunnelRow(new Object[] {1}));
+        Assertions.assertEquals(0, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.never()).commit();
+
+        // Second record hits batch_size: the internal flush must commit without any
+        // prepareCommit, timer flush or close call.
+        writer.write(new SeaTunnelRow(new Object[] {2}));
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.times(1)).commit();
+        Mockito.verify(connection, Mockito.never()).rollback();
+    }
+
+    /** With checkpointing enabled the commit boundary stays at prepareCommit. */
+    @Test
+    void testBatchSizeFlushDoesNotCommitWhenCheckpointEnabled() throws Exception {
+        JdbcDialect dialect = Mockito.mock(JdbcDialect.class);
+        JdbcConnectionProvider connectionProvider = Mockito.mock(JdbcConnectionProvider.class);
+        Connection connection = Mockito.mock(Connection.class);
+        Mockito.when(dialect.dialectName()).thenReturn(DatabaseIdentifier.ORACLE);
+        Mockito.when(dialect.getJdbcConnectionProvider(Mockito.any()))
+                .thenReturn(connectionProvider);
+        Mockito.when(dialect.getRowConverter()).thenReturn(Mockito.mock(JdbcRowConverter.class));
+        Mockito.when(connectionProvider.getConnection()).thenReturn(connection);
+        Mockito.when(connection.getAutoCommit()).thenReturn(false);
+
+        JdbcConnectionConfig connectionConfig =
+                JdbcConnectionConfig.builder()
+                        .driverName(DummyDriver.class.getName())
+                        .url("jdbc:dummy:batch-flush-no-commit")
+                        .autoCommit(true)
+                        .batchSize(2)
+                        .batchIntervalMs(0)
+                        .build();
+        JdbcSinkWriter writer =
+                new JdbcSinkWriter(
+                        null,
+                        Mockito.mock(SinkWriter.Context.class),
+                        dialect,
+                        buildJdbcSinkConfig(connectionConfig),
+                        buildTableSchema(),
+                        buildTableSchema(),
+                        null,
+                        true);
+        Assertions.assertFalse(writer.commitOnFlush);
+
+        CountingExecutor executor = new CountingExecutor();
+        writer.outputFormat =
+                new JdbcOutputFormat<>(connectionProvider, connectionConfig, () -> executor, false);
+
+        writer.write(new SeaTunnelRow(new Object[] {1}));
+        writer.write(new SeaTunnelRow(new Object[] {2}));
+
+        Assertions.assertEquals(1, executor.executeBatchCalls);
+        Mockito.verify(connection, Mockito.never()).commit();
+    }
+
+    private static JdbcSinkConfig buildJdbcSinkConfig(JdbcConnectionConfig jdbcConnectionConfig) {
+        return JdbcSinkConfig.builder()
+                .jdbcConnectionConfig(jdbcConnectionConfig)
+                .simpleSql("INSERT INTO TEST_TABLE(ID) VALUES (?)")
+                .build();
+    }
+
+    private static TableSchema buildTableSchema() {
+        return TableSchema.builder()
+                .column(PhysicalColumn.of("ID", BasicType.INT_TYPE, 22L, false, null, "ID"))
+                .build();
+    }
+
+    private static class CountingExecutor implements JdbcBatchStatementExecutor<SeaTunnelRow> {
+        private int executeBatchCalls;
+
+        @Override
+        public void prepareStatements(Connection connection) {}
+
+        @Override
+        public void addToBatch(SeaTunnelRow record) {}
+
+        @Override
+        public void executeBatch() {
+            executeBatchCalls++;
+        }
+
+        @Override
+        public void closeStatements() {}
+    }
+
+    public static class DummyDriver implements Driver {
+        @Override
+        public Connection connect(String url, Properties info) {
+            return null;
+        }
+
+        @Override
+        public boolean acceptsURL(String url) {
+            return url != null && url.startsWith("jdbc:dummy:");
+        }
+
+        @Override
+        public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) {
+            return new DriverPropertyInfo[0];
+        }
+
+        @Override
+        public int getMajorVersion() {
+            return 1;
+        }
+
+        @Override
+        public int getMinorVersion() {
+            return 0;
+        }
+
+        @Override
+        public boolean jdbcCompliant() {
+            return false;
+        }
+
+        @Override
+        public Logger getParentLogger() throws SQLFeatureNotSupportedException {
+            throw new SQLFeatureNotSupportedException();
+        }
+    }
+
     private static JdbcSinkWriter createWriterWithRowErrorCollector(boolean autoCommit) {
         return createWriterWithRowErrorCollector(autoCommit, new AtomicInteger());
     }