Почему @Transactional терпит неудачу для управляемого приложением EntityManager с EAP 7.2.x и 7.3.x, в то время как 7.1.x работает безупречно?

Следующий простой пример правильно работает с JBoss EAP 7.1.6 (и более ранними версиями), но не работает с EAP 7.2.x и последней версией 7.3.0.

Я создал простой воспроизводимый пример и отправил его на https://github.com/da3x/JBoss-EAP-EntityManager-Problem. Я также связываюсь со службой поддержки Red Hat... но, возможно, кто-то уже решил эту проблему.

Оба метода #save1() и #save2() делают одно и то же с разными EntityManager. Первый управляется приложением, а второй управляется контейнером.

С EAP 7.1.x оба правильно присоединяются к транзакции... с EAP 7.2.x и 7.3.x управляемый приложением не удается сбросить.

package eu.ecg.test;

import java.io.Serializable;

import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

@Named
public class MyBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private static final String VIEW_ID = "/Transactional.xhtml?faces-redirect=true";

    @Inject
    @ApplicationManaged
    private EntityManager em1;

    @Inject
    @ContainerManaged
    private EntityManager em2;

    @Transactional
    public String save1() {
        System.out.println("MyBean.save1()");
        this.em1.flush(); // NOTE: needs Transaction!
        System.out.println("OK!");
        return VIEW_ID;
    }

    @Transactional
    public String save2() {
        System.out.println("MyBean.save2()");
        this.em2.flush(); // NOTE: needs Transaction!
        System.out.println("OK!");
        return VIEW_ID;
    }
}

Оба EntityManager производятся следующим классом:

package eu.ecg.test;

import java.io.Serializable;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.PersistenceUnit;

@ApplicationScoped
public class Persistence implements Serializable {

    private static final long serialVersionUID = 1L;

    @PersistenceUnit(unitName = "example")
    private EntityManagerFactory factory;

    @PersistenceContext(unitName = "example")
    private EntityManager em;

    /**
     * @see PersistenceContextType#EXTENDED
     */
    @Produces
    @ApplicationManaged
    public EntityManager applicationManaged() {
        System.out.println("Persistence.applicationManaged()");
        return this.factory.createEntityManager();
    }

    /**
     * @see PersistenceContextType#TRANSACTION
     */
    @Produces
    @ContainerManaged
    public EntityManager containerManaged() {
        System.out.println("Persistence.containerManaged()");
        return this.em;
    }

}

Этот урезанный пример демонстрирует основную проблему, с которой я столкнулся прямо сейчас. Реальное приложение намного сложнее и состоит из более чем 300 тысяч строк кода, но показывает такое же поведение. Хотя он правильно работает с EAP 7.0.x и 7.1.x, он не работает с 7.2.x и 7.3.0.

Я также знаю, что могу решить эту проблему, добавив em.joinTransaction() к #save1(), но, насколько мне известно, в этом нет необходимости. Аннотация @Transactional должна творить здесь чудеса... не так ли?

Мы используем EntityManager, управляемый приложением, из-за эффективного PersistenceContextType#EXTENDED, который позволяет нам выполнять отложенную загрузку с использованием управляемых объектов вне контекста транзакций — только при чтении данных.

Вот соответствующие журналы:

08:33:14,501 INFO  [stdout] (default task-1) Persistence.applicationManaged()
08:33:14,607 INFO  [stdout] (default task-1) Persistence.containerManaged()
08:33:14,639 INFO  [stdout] (default task-1) MyBean.save2()
08:33:14,648 INFO  [stdout] (default task-1) OK!
08:33:22,113 INFO  [stdout] (default task-1) Persistence.applicationManaged()
08:33:22,113 INFO  [stdout] (default task-1) Persistence.containerManaged()
08:33:22,114 INFO  [stdout] (default task-1) MyBean.save1()
08:33:22,122 WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-1) #{myBean.save1()}: javax.persistence.TransactionRequiredException: no transaction is in progress: javax.faces.FacesException: #{myBean.save1()}: javax.persistence.TransactionRequiredException: no transaction is in progress
    at [email protected]//com.sun.faces.application.ActionListenerImpl.getNavigationOutcome(ActionListenerImpl.java:96)
    at [email protected]//com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:71)
    at [email protected]//javax.faces.component.UICommand.broadcast(UICommand.java:222)
    at [email protected]//javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:847)
    at [email protected]//javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1396)
    at [email protected]//com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:58)
    at [email protected]//com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
    at [email protected]//com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:177)
    at [email protected]//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:707)
    at [email protected]//javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
    at [email protected]//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
    at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
    at [email protected]//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at [email protected]//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at [email protected]//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at [email protected]//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
    at [email protected]//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at [email protected]//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
    at [email protected]//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
    at [email protected]//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at [email protected]//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at [email protected]//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at [email protected]//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at [email protected]//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at [email protected]//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
    at [email protected]//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
    at [email protected]//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at [email protected]//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at [email protected]//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1504)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
    at [email protected]//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
    at [email protected]//io.undertow.server.Connectors.executeRootHandler(Connectors.java:376)
    at [email protected]//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
    at [email protected]//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at [email protected]//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.faces.el.EvaluationException: javax.persistence.TransactionRequiredException: no transaction is in progress
    at [email protected]//com.sun.faces.application.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:76)
    at [email protected]//com.sun.faces.application.ActionListenerImpl.getNavigationOutcome(ActionListenerImpl.java:82)
    ... 57 more
Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress
    at [email protected]//org.hibernate.internal.AbstractSharedSessionContract.checkTransactionNeededForUpdateOperation(AbstractSharedSessionContract.java:398)
    at [email protected]//org.hibernate.internal.SessionImpl.checkTransactionNeededForUpdateOperation(SessionImpl.java:3578)
    at [email protected]//org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1462)
    at [email protected]//org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1458)
    at deployment.A1E-3061.war//eu.ecg.test.MyBean.save1(MyBean.java:28)
    at deployment.A1E-3061.war//eu.ecg.test.MyBean$Proxy$_$$_WeldSubclass.save1$$super(Unknown Source)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at [email protected]//org.jboss.weld.interceptor.proxy.TerminalAroundInvokeInvocationContext.proceedInternal(TerminalAroundInvokeInvocationContext.java:51)
    at [email protected]//org.jboss.weld.interceptor.proxy.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:78)
    at org.jboss.jts//com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:174)
    at org.jboss.jts//com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:53)
    at org.jboss.jts//com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:88)
    at org.jboss.jts//com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:47)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at [email protected]//org.jboss.weld.interceptor.reader.SimpleInterceptorInvocation$SimpleMethodInvocation.invoke(SimpleInterceptorInvocation.java:73)
    at [email protected]//org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke(InterceptorMethodHandler.java:84)
    at [email protected]//org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:72)
    at [email protected]//org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:56)
    at [email protected]//org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:79)
    at [email protected]//org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:68)
    at deployment.A1E-3061.war//eu.ecg.test.MyBean$Proxy$_$$_WeldSubclass.save1(Unknown Source)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at [email protected]//javax.el.ELUtil.invokeMethod(ELUtil.java:245)
    at [email protected]//javax.el.BeanELResolver.invoke(BeanELResolver.java:338)
    at [email protected]//javax.el.CompositeELResolver.invoke(CompositeELResolver.java:198)
    at [email protected]//com.sun.el.parser.AstValue.invoke(AstValue.java:261)
    at [email protected]//com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:280)
    at [email protected]//org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at [email protected]//org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at [email protected]//org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
    at [email protected]//org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at [email protected]//com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:65)
    at [email protected]//com.sun.faces.application.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:66)
    ... 58 more

person Daniel Bleisteiner    schedule 13.05.2020    source источник


Ответы (1)


Служба поддержки Red Hat открыла запросы на вытягивание для EAP 7.2 и 7.3:

До тех пор обходным путем является вызов EntityManger.joinTransaction() перед flush().

person Daniel Bleisteiner    schedule 19.05.2020
comment
Нам дали ранний патч для 7.3.0, который обновляет Hibernate. Пока у нас не было проблем... но тестирование все еще продолжается. - person Daniel Bleisteiner; 26.05.2020
comment
Мы закончили наши тесты без дальнейших проблем. - person Daniel Bleisteiner; 03.06.2020