This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new f30117d95ad3 CAMEL-27284: camel-jpa - JpaMessageIdRepository: a
concurrent add of the same message id returns false on every database (#30531)
f30117d95ad3 is described below
commit f30117d95ad322ce219d7e3590996a52ac258413
Author: allthingssecurity <[email protected]>
AuthorDate: Sat Nov 21 14:38:06 2026 +0530
CAMEL-27284: camel-jpa - JpaMessageIdRepository: a concurrent add of the
same message id returns false on every database (#30531)
When two callers add the same message id at the same time, the insert of
one fails on the unique key. add recognised
that only as SQLIntegrityConstraintViolationException or
EntityExistsException, inside the transaction: on PostgreSQL
and SQL Server (a plain SQLException with SQLState 23xxx, wrapped by
Hibernate) add threw, and with the transaction's
EntityManager the commit of the rollback-only transaction threw after the
duplicate was recognised.
The SQLState class 23 counts as a constraint violation (as in
JpaKeyValueRepository), and the duplicate is also
recognised on the exception of the transaction.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../org/apache/camel/component/jpa/JpaHelper.java | 31 +++
.../idempotent/jpa/JpaMessageIdRepository.java | 113 +++++++--
.../keyvalue/jpa/JpaKeyValueRepository.java | 23 +-
...JpaMessageIdRepositoryConcurrentInsertTest.java | 273 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 18 ++
5 files changed, 413 insertions(+), 45 deletions(-)
diff --git
a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaHelper.java
b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaHelper.java
index 8f63101cc2b3..ab0e5fccbeb7 100644
---
a/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaHelper.java
+++
b/components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaHelper.java
@@ -16,9 +16,12 @@
*/
package org.apache.camel.component.jpa;
+import java.sql.SQLException;
+import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
+import jakarta.persistence.EntityExistsException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
@@ -116,6 +119,34 @@ public final class JpaHelper {
return createDefaultTransactionStrategy(camelContext,
entityManagerFactory);
}
+ /**
+ * Whether the exception, or one of its causes, reports a constraint
violation of the database: an
+ * {@link SQLIntegrityConstraintViolationException}, an {@link
EntityExistsException}, or an {@link SQLException}
+ * with an SQL state of class 23 (integrity constraint violation), as the
PostgreSQL and SQL Server drivers report
+ * it. Any integrity constraint counts, not only a unique key.
+ *
+ * @param ex the exception
+ * @return true if it reports a constraint violation
+ */
+ public static boolean isConstraintViolation(Throwable ex) {
+ Throwable cause = ex;
+ while (cause != null) {
+ if (cause instanceof SQLIntegrityConstraintViolationException) {
+ return true;
+ }
+ if (cause instanceof EntityExistsException) {
+ return true;
+ }
+ // drivers such as the PostgreSQL and SQL Server ones report it
only with the SQL state class 23
+ if (cause instanceof SQLException sqlException &&
sqlException.getSQLState() != null
+ && sqlException.getSQLState().startsWith("23")) {
+ return true;
+ }
+ cause = cause.getCause();
+ }
+ return false;
+ }
+
/**
* Copy JpaConstants.ENTITY_MANAGER property from source to target
exchange.
*
diff --git
a/components/camel-jpa/src/main/java/org/apache/camel/processor/idempotent/jpa/JpaMessageIdRepository.java
b/components/camel-jpa/src/main/java/org/apache/camel/processor/idempotent/jpa/JpaMessageIdRepository.java
index 8905ef388137..bc263ef3a5d3 100644
---
a/components/camel-jpa/src/main/java/org/apache/camel/processor/idempotent/jpa/JpaMessageIdRepository.java
+++
b/components/camel-jpa/src/main/java/org/apache/camel/processor/idempotent/jpa/JpaMessageIdRepository.java
@@ -38,6 +38,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.component.jpa.JpaHelper.getTargetEntityManager;
+import static org.apache.camel.component.jpa.JpaHelper.isConstraintViolation;
@ManagedResource(description = "JPA based message id repository")
public class JpaMessageIdRepository extends ServiceSupport implements
IdempotentRepository {
@@ -83,12 +84,65 @@ public class JpaMessageIdRepository extends ServiceSupport
implements Idempotent
return add(null, messageId);
}
+ /**
+ * Adds the message id if it is not in the repository. When the insert
fails with a constraint violation, which
+ * happens when another caller (thread, node) inserts the same message id
at the same time, the message id is read
+ * again with a new EntityManager in a new transaction: add returns false
if it is there, and throws otherwise (for
+ * example after a primary key collision, when the id sequence is behind
the table). In a transaction of the caller,
+ * the message id is read again in that transaction (with the same
EntityManager when it is shared), which the
+ * failed insert has marked for rollback: add may then throw, and the
caller's transaction fails.
+ */
@Override
public boolean add(final Exchange exchange, final String messageId) {
final EntityManager entityManager
= getTargetEntityManager(exchange, entityManagerFactory,
false, sharedEntityManager, true);
- // Run this in single transaction.
final Boolean[] rc = new Boolean[1];
+ final Exception[] violation = new Exception[1];
+ // what add throws when the message id is not stored after a
constraint violation
+ RuntimeException failure = null;
+ try {
+ doAdd(entityManager, messageId, rc, violation);
+ } catch (RuntimeException e) {
+ // the transaction could not commit after the insert failed on a
constraint (the failed flush marked it for
+ // rollback, and the commit failure, such as an
UnexpectedRollbackException, may not say why), or the
+ // constraint violation came at commit
+ if (violation[0] == null && !isConstraintViolation(e)) {
+ throw e;
+ }
+ failure = e;
+ }
+
+ if (violation[0] != null) {
+ String contextInfo = String.format(SOMETHING_WENT_WRONG,
violation[0].getMessage());
+ PersistenceException wrapped = new
PersistenceException(contextInfo, violation[0]);
+ if (failure != null) {
+ wrapped.addSuppressed(failure);
+ }
+ failure = wrapped;
+ }
+ if (failure != null) {
+ // the SQL state class 23 covers every integrity violation, not
only the unique key on processorName and
+ // messageId. When the database reports the violation of that key,
the other caller's insert has committed,
+ // so a new transaction sees its row
+ boolean stored;
+ try {
+ stored = isStored(messageId);
+ } catch (RuntimeException e) {
+ e.addSuppressed(failure);
+ throw e;
+ }
+ if (!stored) {
+ throw failure;
+ }
+ LOG.debug("Duplicate message detected during concurrent insert:
{}", messageId);
+ rc[0] = Boolean.FALSE;
+ }
+
+ LOG.debug("add {} -> {}", messageId, rc[0]);
+ return rc[0];
+ }
+
+ private void doAdd(EntityManager entityManager, String messageId,
Boolean[] rc, Exception[] violation) {
transactionStrategy.executeInTransaction(() -> {
if (isJoinTransaction()) {
entityManager.joinTransaction();
@@ -109,26 +163,43 @@ public class JpaMessageIdRepository extends
ServiceSupport implements Idempotent
}
} catch (Exception ex) {
if (isConstraintViolation(ex)) {
- // concurrent insert of the same messageId detected via
unique constraint
- // treat as duplicate rather than failing the exchange
- LOG.debug("Duplicate message detected during concurrent
insert: {}", messageId);
- rc[0] = Boolean.FALSE;
+ // possibly a concurrent insert of the same messageId: add
checks it in a new transaction
+ violation[0] = ex;
} else {
String contextInfo = String.format(SOMETHING_WENT_WRONG,
ex.getMessage());
throw new PersistenceException(contextInfo, ex);
}
} finally {
- try {
- if (entityManager.isOpen()) {
- entityManager.close();
- }
- } catch (Exception e) {
- // ignore
- }
+ closeEntityManager(entityManager);
}
});
+ }
- LOG.debug("add {} -> {}", messageId, rc[0]);
+ /**
+ * Whether the message id is in the repository.
+ * <p>
+ * Without a caller's transaction, it is read in a new transaction, after
the transaction of the insert ended.
+ * <p>
+ * In a caller's transaction, it is read in that transaction: with the
EntityManager of that transaction when the
+ * EntityManager is shared, otherwise with a new EntityManager.
+ */
+ private boolean isStored(String messageId) {
+ final EntityManager entityManager
+ = getTargetEntityManager(null, entityManagerFactory, false,
sharedEntityManager, true);
+ final boolean[] rc = new boolean[1];
+ transactionStrategy.executeInTransaction(() -> {
+ if (isJoinTransaction()) {
+ entityManager.joinTransaction();
+ }
+ try {
+ rc[0] = !query(entityManager, messageId).isEmpty();
+ } catch (Exception ex) {
+ String contextInfo = String.format(SOMETHING_WENT_WRONG,
ex.getMessage());
+ throw new PersistenceException(contextInfo, ex);
+ } finally {
+ closeEntityManager(entityManager);
+ }
+ });
return rc[0];
}
@@ -304,18 +375,14 @@ public class JpaMessageIdRepository extends
ServiceSupport implements Idempotent
this.sharedEntityManager = sharedEntityManager;
}
- private static boolean isConstraintViolation(Exception ex) {
- Throwable cause = ex;
- while (cause != null) {
- if (cause instanceof
java.sql.SQLIntegrityConstraintViolationException) {
- return true;
- }
- if (cause instanceof jakarta.persistence.EntityExistsException) {
- return true;
+ private static void closeEntityManager(EntityManager entityManager) {
+ try {
+ if (entityManager.isOpen()) {
+ entityManager.close();
}
- cause = cause.getCause();
+ } catch (Exception e) {
+ // ignore
}
- return false;
}
@Override
diff --git
a/components/camel-jpa/src/main/java/org/apache/camel/processor/keyvalue/jpa/JpaKeyValueRepository.java
b/components/camel-jpa/src/main/java/org/apache/camel/processor/keyvalue/jpa/JpaKeyValueRepository.java
index 08e2ed6f67ae..ff5218ec01f1 100644
---
a/components/camel-jpa/src/main/java/org/apache/camel/processor/keyvalue/jpa/JpaKeyValueRepository.java
+++
b/components/camel-jpa/src/main/java/org/apache/camel/processor/keyvalue/jpa/JpaKeyValueRepository.java
@@ -16,14 +16,11 @@
*/
package org.apache.camel.processor.keyvalue.jpa;
-import java.sql.SQLException;
-import java.sql.SQLIntegrityConstraintViolationException;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
-import jakarta.persistence.EntityExistsException;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.PersistenceException;
@@ -44,6 +41,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.component.jpa.JpaHelper.getTargetEntityManager;
+import static org.apache.camel.component.jpa.JpaHelper.isConstraintViolation;
/**
* A JPA-based {@link KeyValueRepository} that stores entries as {@link
KeyValueEntry} entities.
@@ -540,23 +538,4 @@ public class JpaKeyValueRepository extends ServiceSupport
implements KeyValueRep
// ignore
}
}
-
- private static boolean isConstraintViolation(Exception ex) {
- Throwable cause = ex;
- while (cause != null) {
- if (cause instanceof SQLIntegrityConstraintViolationException) {
- return true;
- }
- if (cause instanceof EntityExistsException) {
- return true;
- }
- // drivers such as the PostgreSQL and SQL Server ones report it
only with the SQL state class 23
- if (cause instanceof SQLException sqlException &&
sqlException.getSQLState() != null
- && sqlException.getSQLState().startsWith("23")) {
- return true;
- }
- cause = cause.getCause();
- }
- return false;
- }
}
diff --git
a/components/camel-jpa/src/test/java/org/apache/camel/processor/idempotent/jpa/JpaMessageIdRepositoryConcurrentInsertTest.java
b/components/camel-jpa/src/test/java/org/apache/camel/processor/idempotent/jpa/JpaMessageIdRepositoryConcurrentInsertTest.java
new file mode 100644
index 000000000000..d273d78579e3
--- /dev/null
+++
b/components/camel-jpa/src/test/java/org/apache/camel/processor/idempotent/jpa/JpaMessageIdRepositoryConcurrentInsertTest.java
@@ -0,0 +1,273 @@
+/*
+ * 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.camel.processor.idempotent.jpa;
+
+import java.sql.SQLException;
+import java.sql.SQLIntegrityConstraintViolationException;
+import java.util.List;
+
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.PersistenceException;
+import jakarta.persistence.Query;
+import jakarta.persistence.RollbackException;
+
+import org.apache.camel.component.jpa.TransactionStrategy;
+import org.hibernate.exception.ConstraintViolationException;
+import org.hibernate.exception.JDBCConnectionException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.transaction.TransactionSystemException;
+import org.springframework.transaction.UnexpectedRollbackException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Two callers add the same message id at the same time: both find no row, and
the insert of one fails on the unique
+ * key. The repository must answer that the message id is a duplicate (add
returns false) whatever the database driver
+ * reports and whether the failure comes at the flush or when the transaction
commits. As a constraint violation can
+ * also be on another constraint (such as a primary key collision when the id
sequence is behind the table), the
+ * repository reads the message id again with a new EntityManager in a new
transaction, and fails when it is not there.
+ */
+class JpaMessageIdRepositoryConcurrentInsertTest {
+
+ private final EntityManagerFactory emf = mock(EntityManagerFactory.class);
+ // the EntityManager of the insert
+ private final EntityManager em = mock(EntityManager.class);
+ // the EntityManager that reads the message id again after a constraint
violation
+ private final EntityManager reread = mock(EntityManager.class);
+ private final Transactions transactions = new Transactions();
+ // the transaction in which the message id was read again (0: not read
again)
+ private int rereadInTransaction;
+
+ @BeforeEach
+ void setUp() {
+ // the other caller has not committed yet when the insert reads: no row
+ Query query = mock(Query.class);
+ when(query.setParameter(anyInt(), any())).thenReturn(query);
+ when(query.getResultList()).thenReturn(List.of());
+ when(em.createQuery(anyString())).thenReturn(query);
+ when(em.isOpen()).thenReturn(true);
+ when(reread.isOpen()).thenReturn(true);
+ when(emf.createEntityManager()).thenReturn(em, reread);
+ }
+
+ @Test
+ void postgresDuplicateKeyIsDuplicate() {
+ // a PostgreSQL unique violation: the driver's PSQLException is a
plain SQLException
+ failFlushWith(new SQLException("duplicate key value violates unique
constraint", "23505"));
+ storedByOtherCaller(true);
+
+ assertFalse(repository(transactions).add("1"));
+ // read again with a new EntityManager, in a transaction of its own
after the one of the insert
+ verify(emf, times(2)).createEntityManager();
+ assertEquals(2, rereadInTransaction);
+ assertFalse(transactions.nested);
+ }
+
+ @Test
+ void sqlServerDuplicateKeyIsDuplicate() {
+ failFlushWith(new SQLException("Violation of UNIQUE KEY constraint",
"23000", 2627));
+ storedByOtherCaller(true);
+
+ assertFalse(repository(transactions).add("1"));
+ assertEquals(2, rereadInTransaction);
+ }
+
+ @Test
+ void integrityConstraintViolationExceptionIsDuplicate() {
+ // drivers such as the H2, Derby, MySQL and Oracle ones throw this
subclass
+ failFlushWith(new SQLIntegrityConstraintViolationException("Unique
index or primary key violation", "23505"));
+ storedByOtherCaller(true);
+
+ assertFalse(repository(transactions).add("1"));
+ assertEquals(2, rereadInTransaction);
+ }
+
+ @Test
+ void duplicateWhenTheTransactionCannotCommit() {
+ failFlushWith(new SQLIntegrityConstraintViolationException("Unique
index or primary key violation", "23505"));
+ storedByOtherCaller(true);
+ // the failed flush marked the transaction for rollback (a shared
EntityManager of the transaction), so the
+ // commit fails: Spring's JpaTransactionManager throws this exception,
without a cause
+ transactions.firstCommitFailure = markedForRollback();
+
+ assertFalse(repository(transactions).add("1"));
+ assertEquals(2, rereadInTransaction);
+ }
+
+ @Test
+ void primaryKeyCollisionFails() {
+ // the id sequence is behind the table: PostgreSQL reports the primary
key collision with 23505 as well, and the
+ // message id is not in the table
+ failFlushWith(new SQLException(
+ "duplicate key value violates unique constraint
\"camel_messageprocessed_pkey\"",
+ "23505"));
+ storedByOtherCaller(false);
+
+ PersistenceException e = assertThrows(PersistenceException.class, ()
-> repository(transactions).add("1"));
+ assertInstanceOf(ConstraintViolationException.class, e.getCause());
+ assertEquals(2, rereadInTransaction);
+ }
+
+ @Test
+ void primaryKeyCollisionWhenTheTransactionCannotCommitFails() {
+ failFlushWith(new SQLException("Violation of PRIMARY KEY constraint",
"23000", 2627));
+ storedByOtherCaller(false);
+ UnexpectedRollbackException commitFailure = markedForRollback();
+ transactions.firstCommitFailure = commitFailure;
+
+ // the constraint violation is thrown, as the commit failure does not
say why, and the commit failure is kept
+ PersistenceException e = assertThrows(PersistenceException.class, ()
-> repository(transactions).add("1"));
+ assertInstanceOf(ConstraintViolationException.class, e.getCause());
+ assertSame(commitFailure, e.getSuppressed()[0]);
+ assertEquals(2, rereadInTransaction);
+ }
+
+ @Test
+ void violationAtCommitIsDuplicate() {
+ // the constraint violation comes when the transaction commits (such
as a deferred constraint)
+ transactions.firstCommitFailure = commitFailsWith(new
SQLException("duplicate key value", "23505"));
+ storedByOtherCaller(true);
+
+ assertFalse(repository(transactions).add("1"));
+ assertEquals(2, rereadInTransaction);
+ }
+
+ @Test
+ void violationAtCommitNotStoredFails() {
+ TransactionSystemException commitFailure = commitFailsWith(new
SQLException("duplicate key value", "23505"));
+ transactions.firstCommitFailure = commitFailure;
+ storedByOtherCaller(false);
+
+ TransactionSystemException e
+ = assertThrows(TransactionSystemException.class, () ->
repository(transactions).add("1"));
+ assertSame(commitFailure, e);
+ assertEquals(2, rereadInTransaction);
+ }
+
+ @Test
+ void readAgainFailureFails() {
+ failFlushWith(new SQLException("duplicate key value violates unique
constraint", "23505"));
+ Query query = mock(Query.class);
+ when(query.setParameter(anyInt(), any())).thenReturn(query);
+ when(query.getResultList()).thenThrow(new JDBCConnectionException(
+ "could not execute query", new SQLException("Connection
reset", "08006")));
+ when(reread.createQuery(anyString())).thenReturn(query);
+
+ // the failure of the read is thrown, with the constraint violation
kept
+ PersistenceException e = assertThrows(PersistenceException.class, ()
-> repository(transactions).add("1"));
+ assertInstanceOf(JDBCConnectionException.class, e.getCause());
+ assertInstanceOf(ConstraintViolationException.class,
e.getSuppressed()[0].getCause());
+ }
+
+ @Test
+ void otherDatabaseFailureFails() {
+ doThrow(new JDBCConnectionException(
+ "could not execute statement", new SQLException("Connection
reset", "08006"))).when(em).flush();
+
+ assertThrows(PersistenceException.class, () ->
repository(transactions).add("1"));
+ verify(emf, times(1)).createEntityManager();
+ }
+
+ @Test
+ void otherCommitFailureFails() {
+ transactions.firstCommitFailure
+ = new TransactionSystemException("Could not commit JPA
transaction", new RollbackException("Commit failed"));
+
+ assertThrows(TransactionSystemException.class, () ->
repository(transactions).add("1"));
+ verify(emf, times(1)).createEntityManager();
+ }
+
+ @Test
+ void newMessageIdIsAdded() {
+ assertTrue(repository(transactions).add("1"));
+ verify(emf, times(1)).createEntityManager();
+ }
+
+ private void failFlushWith(SQLException sqlException) {
+ // Hibernate 7 throws its JDBCException subclass (a
PersistenceException) with the driver's exception as cause
+ doThrow(new ConstraintViolationException("could not execute
statement", sqlException, "uk_processor_message"))
+ .when(em).flush();
+ }
+
+ private static UnexpectedRollbackException markedForRollback() {
+ return new UnexpectedRollbackException("Transaction silently rolled
back because it has been marked as rollback-only");
+ }
+
+ private static TransactionSystemException commitFailsWith(SQLException
sqlException) {
+ // a commit failure with the constraint violation in its cause chain
(JpaTransactionManager translates it, such
+ // as into a JpaSystemException; TransactionSystemException is its
fallback)
+ return new TransactionSystemException(
+ "Could not commit JPA transaction", new RollbackException(
+ "Error while committing the transaction",
+ new ConstraintViolationException("could not execute
statement", sqlException, "uk_processor_message")));
+ }
+
+ private void storedByOtherCaller(boolean stored) {
+ // the read in a new transaction sees the row of the other caller,
which has committed by then
+ Query query = mock(Query.class);
+ when(query.setParameter(anyInt(), any())).thenReturn(query);
+ when(query.getResultList()).thenAnswer(invocation -> {
+ rereadInTransaction = transactions.count;
+ return stored ? List.of(new MessageProcessed()) : List.of();
+ });
+ when(reread.createQuery(anyString())).thenReturn(query);
+ }
+
+ private JpaMessageIdRepository repository(TransactionStrategy
transactionStrategy) {
+ return new JpaMessageIdRepository(emf, transactionStrategy,
"myProcessor");
+ }
+
+ /**
+ * Runs each unit of work as a transaction of its own, and fails the
commit of the first one when asked.
+ */
+ private static final class Transactions implements TransactionStrategy {
+ private int count;
+ private boolean active;
+ private boolean nested;
+ private RuntimeException firstCommitFailure;
+
+ @Override
+ public void executeInTransaction(Runnable runnable) {
+ nested |= active;
+ active = true;
+ count++;
+ try {
+ runnable.run();
+ } finally {
+ active = false;
+ }
+ if (count == 1 && firstCommitFailure != null) {
+ throw firstCommitFailure;
+ }
+ }
+ }
+}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index fb7dff1a864c..ab02cb5282cb 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -9746,6 +9746,24 @@ failed three times. A constraint violation is also
recognised by its SQL state (
Server drivers report it. When `putIfAbsent` runs in a transaction of the
caller, the failed insert marks that
transaction for rollback, so the caller's transaction fails, as before.
+=== camel-jpa - JpaMessageIdRepository: add after a constraint violation
+
+When the insert of `JpaMessageIdRepository.add` fails with a constraint
violation, the message id is now read again with
+a new EntityManager in a new transaction: `add` returns `false` if the message
id is there (another caller added it at
+the same time), and throws otherwise, for example after a primary key
collision when the id sequence is behind the
+table. A constraint violation is now also recognised by its SQL state (class
`23`), as the PostgreSQL and SQL Server
+drivers report it, and also when the transaction then fails to commit. So on
PostgreSQL and SQL Server, `add` now
+returns `false` for a message id that another caller added at the same time,
where it threw a `PersistenceException`
+before. With `sharedEntityManager=true`, `add` failed for such a message id on
every database, as the failed insert
+marked the transaction for rollback and its commit then threw (an
`UnexpectedRollbackException` with a Spring based
+transaction strategy); it now returns `false` there too. On H2, Derby, MySQL
and Oracle with an EntityManager that is
+not shared, which returned `false` for any constraint violation, `add` now
throws when the message id is not in the
+table after the violation.
+
+When `add` runs in a transaction of the caller, the message id is read again
in that transaction (with the same
+EntityManager when it is shared), which the failed insert has marked for
rollback. `add` may then throw where it
+returned `false` before, and the caller's transaction fails, as before.
+
=== camel-jbang - the export to Quarkus keeps camel-quarkus-microprofile-health
`camel export --runtime=quarkus`, and `camel run --runtime=quarkus`, which
exports the same way, now write