[
https://issues.apache.org/jira/browse/OPENJPA-3090?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
]
Richard Zowalla resolved OPENJPA-3090.
--------------------------------------
Fix Version/s: 4.3.0
Resolution: Fixed
> EntityManagerFactory.callInTransaction() throws for any non-entity result,
> after the transaction has committed
> --------------------------------------------------------------------------------------------------------------
>
> Key: OPENJPA-3090
> URL: https://issues.apache.org/jira/browse/OPENJPA-3090
> Project: OpenJPA
> Issue Type: Bug
> Components: jpa
> Affects Versions: 4.2.0
> Environment: OpenJPA 4.2.0 (also present on master as of 2026-11-20),
> JDK 17.0.20, H2 2.5.252, entities enhanced at build time
> Reporter: Paul King
> Priority: Major
> Fix For: 4.3.0
>
>
> h3. Description
> {{EntityManagerFactory.callInTransaction(Function<EntityManager,R>)}} (new in
> Jakarta Persistence 3.2) only works when the function returns an entity
> instance or {{null}}. Returning any other value, such as a {{String}}, a
> {{Long}} from a count query, or a {{List}} from {{getResultList()}}, fails
> with:
> {noformat}
> <openjpa-4.2.0-r977f0cb fatal general error>
> org.apache.openjpa.persistence.PersistenceException: The class "class
> java.lang.String" is not an entity.
> Caused by: <openjpa-4.2.0-r977f0cb fatal user error>
> org.apache.openjpa.persistence.ArgumentException: The class "class
> java.lang.String" is not an entity.
> at
> org.apache.openjpa.persistence.EntityManagerImpl.contains(EntityManagerImpl.java:1112)
> at
> org.apache.openjpa.persistence.EntityManagerFactoryImpl.callInTransaction(EntityManagerFactoryImpl.java:906)
> {noformat}
> The failure happens *after* the transaction has committed. The caller gets a
> "fatal" exception even though the work was persisted.
> {{runInTransaction()}} is not affected, because it delegates to
> {{callInTransaction()}} with a function that returns {{null}}.
> h3. Steps to reproduce
> {code:java|title=Author.java}
> package repro;
> import jakarta.persistence.*;
> @Entity
> public class Author {
> @Id @GeneratedValue
> private Long id;
> private String name;
> protected Author() { }
> public Author(String name) { this.name = name; }
> public Long getId() { return id; }
> public String getName() { return name; }
> }
> {code}
> {code:java|title=CallInTransactionRepro.java}
> package repro;
> import jakarta.persistence.*;
> public class CallInTransactionRepro {
> public static void main(String[] args) {
> try (EntityManagerFactory emf = Repro.emf()) {
> // 1. Returning an entity works
> Author author = emf.callInTransaction(em -> {
> Author a = new Author("Dierk");
> em.persist(a);
> return a;
> });
> System.out.println("entity result: " + author.getName());
> // 2. Returning a non-entity value (here a String) fails
> try {
> String name = emf.callInTransaction(em -> {
> em.persist(new Author("Guillaume"));
> return "Guillaume";
> });
> System.out.println("String result: " + name);
> } catch (PersistenceException e) {
> System.out.println("String result failed: " + e);
> }
> // 3. ...yet the transaction in step 2 was committed
> try (EntityManager em = emf.createEntityManager()) {
> long count = em.createQuery(
> "select count(a) from Author a where a.name =
> 'Guillaume'", Long.class)
> .getSingleResult();
> System.out.println("Guillaume rows: " + count);
> }
> }
> }
> }
> {code}
> {code:java|title=Repro.java}
> package repro;
> import jakarta.persistence.*;
> final class Repro {
> private Repro() { }
> static EntityManagerFactory emf() {
> return new PersistenceConfiguration("repro")
>
> .provider("org.apache.openjpa.persistence.PersistenceProviderImpl")
> .managedClass(Author.class)
> .managedClass(Gadget.class)
> .property(PersistenceConfiguration.JDBC_DRIVER, "org.h2.Driver")
> .property(PersistenceConfiguration.JDBC_URL,
> "jdbc:h2:mem:repro;DB_CLOSE_DELAY=-1")
> .property("openjpa.jdbc.SynchronizeMappings",
> "buildSchema(ForeignKeys=true)")
> .property("openjpa.RuntimeUnenhancedClasses", "unsupported")
> .property("openjpa.Log", "DefaultLevel=WARN")
> .createEntityManagerFactory();
> }
> }
> {code}
> {{Author}} is enhanced at build time with {{PCEnhancer}} before running.
> ({{Repro.emf()}} also lists a second entity, {{Gadget}}, shared with another
> repro. It has the same shape as {{Author}} and isn't needed for this bug.)
> h3. Actual output
> {noformat}
> entity result: Dierk
> String result failed: <openjpa-4.2.0-r977f0cb fatal general error>
> org.apache.openjpa.persistence.PersistenceException: The class "class
> java.lang.String" is not an entity.
> Guillaume rows: 1
> {noformat}
> h3. Expected output
> {noformat}
> entity result: Dierk
> String result: Guillaume
> Guillaume rows: 1
> {noformat}
> The specification places no restriction on the result type {{R}}.
> h3. Analysis
> In {{EntityManagerFactoryImpl.callInTransaction()}}, after the commit:
> {code:java}
> if (result != null
> && !(result instanceof PersistenceCapable)
> && em.contains(result)) {
> {code}
> {{EntityManager.contains()}} is specified to throw
> {{IllegalArgumentException}} when its argument is not an entity, so it can't
> be used to ask "is this an entity?". The exception escapes into the outer
> {{catch}}, which tries a rollback (the transaction has already committed) and
> wraps it in a {{PersistenceException}}.
> h3. Background
> The re-find block was discussed in the review of the Jakarta Persistence 3.2
> PR: https://github.com/apache/openjpa/pull/144#discussion_r3683004050. The
> reviewer suggested dropping the block or limiting it to runtime-unenhanced
> types. It was instead gated to "results that are not enhanced classes"
> ({{!(result instanceof PersistenceCapable)}}). That condition is also true
> for every non-entity value, so all of them now reach {{em.contains()}}.
> h3. Suggested fix
> Only call {{em.contains(result)}} when the result's class is an entity type.
> The patch below applies cleanly to master (2e70610):
> {code:diff}
> ---
> a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
> +++
> b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/EntityManagerFactoryImpl.java
> @@ -61,6 +61,7 @@
> import org.apache.openjpa.lib.util.Closeable;
> import org.apache.openjpa.lib.util.Localizer;
> import org.apache.openjpa.lib.util.StringUtil;
> +import org.apache.openjpa.meta.ClassMetaData;
> import org.apache.openjpa.meta.EntityGraphMetaData;
> import org.apache.openjpa.meta.MetaDataModes;
> import org.apache.openjpa.meta.MetaDataRepository;
> @@ -903,6 +904,7 @@
> // to OpenJPAPersistenceUtil#toPC
> if (result != null
> && !(result instanceof PersistenceCapable)
> + && isEntityType(result.getClass())
> && em.contains(result)) {
> try {
> Object id =
> getPersistenceUnitUtil().getIdentifier(result);
> @@ -937,6 +939,16 @@
> } finally {
> em.close();
> }
> + }
> +
> + /**
> + * Whether instances of the given class are entities, i.e. something
> + * {@link EntityManager#contains} accepts rather than rejects.
> + */
> + private boolean isEntityType(Class<?> cls) {
> + ClassMetaData meta =
> getConfiguration().getMetaDataRepositoryInstance()
> + .getMetaData(cls, null, false);
> + return meta != null && !meta.isEmbeddedOnly();
> }
>
> @Override
> {code}
> I tested it by putting the patched class ahead of the 4.2.0 jars, with
> build-time enhanced entities and with {{RuntimeUnenhancedClasses=supported}}.
> {{String}}, {{Long}}, {{List}} and {{null}} results are returned as-is.
> Entity results (persisted or found) behave as before, including the re-find
> of runtime subclasses. A function that throws still rolls back. The repro
> above prints the expected output.
> I also built master (2e70610) with and without the patch and ran the related
> upstream tests on the default test database: TestEJBQLFunction,
> TestInMemoryScalarExpressions, TestPreparedQueryCache,
> TestPreparedQueryCacheExclusion, both TestQuerySQLCache classes,
> TestNamedCriteriaQueryWithSQLCache, TestEntityManagerFactoryTransactions,
> TestEntityManagerFactoryTCK and TestPersistenceUnitUtil. All 212 tests pass
> in both runs (2 skipped in both).
> Two follow-ups are worth considering:
> * Whether the post-commit re-find is needed at all. The PR #144 review asked
> for it to be dropped or limited to runtime-unenhanced types.
> * Moving any post-commit work out of the {{try}} whose {{catch}} does the
> rollback, so a failure after commit can't be reported as a failed transaction.
> h3. Related
> No existing issue found (searched JIRA for
> callInTransaction/runInTransaction/"is not an entity" and GitHub PRs as of
> 2026-11-20). The other review points on the same method were addressed in PR
> #144 itself.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)