2 Replies Latest reply on Mar 15, 2012 1:49 PM by Dominik Grupp

    Transaction demarcation - automatic flush

    Dominik Grupp Newbie

      Hello,

       

      based on the quickstart examples which come with jboss as 7.1 I created the example below. Problem: although e.g. a select on the database during the login process works fine a new user is not persisted. In the Dao the method to persist the user is called but nothing seems to happen. I thought probably the transaction is not managed and added a commit but got "java.sql.SQLException: You cannot commit during a managed transaction!". As I learned the developer does not need to care about transaction management when the class is decorated with @Stateful. Why is a user entity not persisted? No logging statements regarding sql are printed.

       

      Regards,

       

      Michael

          

      Backing bean

       

      package de.comp.admin;

       

      import javax.annotation.PostConstruct;

      import javax.ejb.Stateful;

      import javax.enterprise.context.RequestScoped;

      import javax.enterprise.inject.Produces;

      import javax.inject.Inject;

      import javax.inject.Named;

      import org.apache.log4j.Logger;

      import de.comp.domain.User;

      import de.comp.service.UserManager;

       

      @Named

      @Stateful

      @RequestScoped

      public class UserCreate {

       

                final static Logger logger = Logger.getLogger(UserCreate.class);

       

                @Inject

                private UserManager userManager;

       

                private User newUser;

       

                public void saveUser()  throws Exception {

                          logger.trace("Now trying to save user " + newUser.toString());

                          userManager.save(newUser);

                          initNewUser();

                }

       

                @PostConstruct

                public void initNewUser() {

                          newUser = new User();

                }

       

                @Produces

                @Named

                public User getNewUser() {

                          return newUser;

                }

      }

       

       

      User Manager

       

      package de.comp.service.impl;

       

      import java.util.List;

      import javax.ejb.Stateful;

      import javax.enterprise.context.RequestScoped;

      import javax.inject.Inject;

      import javax.inject.Named;

      import de.comp.dao.UserDao;

      import de.comp.domain.User;

      import de.comp.service.UserManager;

       

      @Named("userManager")

      @RequestScoped

      @Stateful

      public class UserManagerImpl implements UserManager {

       

                @Inject

                private UserDao userDao;

       

                public void save(User user) throws Exception {

                          userDao.persist(user);

                }

       

                public User findUser(String username, String password) throws Exception {

                          List<User> userList = userDao.findByLogPwd(username, password);

                          if (userList.isEmpty()) {

                                    return null;

                          } else if (userList.size() > 1) {

                                    throw new IllegalStateException("Cannot have more than one user with the same username!");

                          } else {

                                    return userList.get(0);

                          }

                }

      }

       

      User Dao

       

      package de.comp.dao.impl;

       

      import java.util.Iterator;

      import java.util.List;

      import javax.ejb.Stateful;

      import javax.enterprise.context.RequestScoped;

      import javax.inject.Inject;

      import javax.persistence.EntityManager;

      import org.apache.log4j.Logger;

      import de.comp.dao.UserDao;

      import de.comp.domain.User;

       

      @RequestScoped

      @Stateful

      public class JpaUserDao implements UserDao {

       

                final static Logger logger = Logger.getLogger(JpaUserDao.class);

                private static final String ALL_USERS = "from de.comp.domain.User s order by s.lastname";

                private static final String USER_BY_LOGIN = "from de.comp.domain.User s where s.loginname = :loginparam";

                private static final String USER_BY_LOGIN_PWD = "from de.comp.domain.User u where u.loginname = :loginparam and u.pwd = :passwordparam";

       

                @Inject

                private EntityManager em;

       

                public void persist(User user) throws Exception {

                          logger.trace("Now persisting user " + user.toString());

                          em.persist(user);

                }

       

                public List<User> findByLogPwd(String username, String pwd) throws Exception {

                          @SuppressWarnings("unchecked")

                          List<User> userList = em.createQuery(USER_BY_LOGIN_PWD).setParameter("loginparam", username).setParameter("passwordparam", pwd)

                                              .getResultList();

                          return userList;

                }

       

                public User merge(User user) {

                          return em.merge(user);

                }

      }

       

      persistence.xml

       

      <persistence xmlns="http://java.sun.com/xml/ns/persistence"

                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

                xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"

                version="1.0">

                <persistence-unit name="jatPU" transaction-type="RESOURCE_LOCAL">

                          <provider>org.hibernate.ejb.HibernatePersistence</provider>

                          <jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>

                          <properties>

                                    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />

                                    <property name="hibernate.show_sql" value="true" />

                                    <property name="hibernate.format_sql" value="true" />

                                    <property name="hibernate.use_sql_comments" value="true" />

                                    <property name="hibernate.hbm2ddl.auto" value="validate" />

                          </properties>

                </persistence-unit>

      </persistence>

       

      Output during deployment

       

      17:47:15,177 INFO  [org.jboss.as.repository] (management-handler-threads - 44) JBAS014900: Content added at location /Users/grudom/Programme/jboss/jboss-as-7.1.0.Final/standalone/data/content/8d/431d7d942858dc98fd112c613288260b59db2a/content

      17:47:15,188 INFO  [org.jboss.weld.deployer] (MSC service thread 1-5) JBAS016009: Stopping weld service for deployment admshow.war

      17:47:15,190 INFO  [org.jboss.as.jpa] (MSC service thread 1-11) JBAS011403: Stopping Persistence Unit Service 'admshow.war#jatPU'

      17:47:15,210 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-3) JBAS015877: Stopped deployment admshow.war in 31ms

      17:47:15,211 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of "admshow.war"

      17:47:16,332 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) JBAS015893: Encountered invalid class name 'implClass=org.jboss.shrinkwrap.resolver.impl.maven.MavenBuilderImpl' for service type 'org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver'

      17:47:16,334 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-8) JBAS015893: Encountered invalid class name 'implClass=org.jboss.shrinkwrap.resolver.impl.maven.MavenImpl' for service type 'org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolverShortcutAPI'

      17:47:16,341 INFO  [org.jboss.as.jpa] (MSC service thread 1-8) JBAS011401: Read persistence.xml for jatPU

      17:47:16,821 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-10) JBAS015877: Stopped deployment admshow.war in 1608ms

      17:47:16,822 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-4) JBAS015876: Starting deployment of "admshow.war"

      17:47:17,929 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-12) JBAS015893: Encountered invalid class name 'implClass=org.jboss.shrinkwrap.resolver.impl.maven.MavenBuilderImpl' for service type 'org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver'

      17:47:17,980 WARN  [org.jboss.as.server.deployment] (MSC service thread 1-12) JBAS015893: Encountered invalid class name 'implClass=org.jboss.shrinkwrap.resolver.impl.maven.MavenImpl' for service type 'org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolverShortcutAPI'

      17:47:17,988 INFO  [org.jboss.as.jpa] (MSC service thread 1-12) JBAS011401: Read persistence.xml for jatPU

      17:47:18,016 INFO  [org.jboss.weld.deployer] (MSC service thread 1-9) JBAS016002: Processing weld deployment admshow.war

      17:47:18,017 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-9) JNDI bindings for session bean named UserManagerImpl in deployment unit deployment "admshow.war" are as follows:

       

       

                java:global/admshow/UserManagerImpl!de.comp.service.UserManager

                java:app/admshow/UserManagerImpl!de.comp.service.UserManager

                java:module/UserManagerImpl!de.comp.service.UserManager

                java:global/admshow/UserManagerImpl

                java:app/admshow/UserManagerImpl

                java:module/UserManagerImpl

       

       

      17:47:18,026 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-9) JNDI bindings for session bean named JpaUserDao in deployment unit deployment "admshow.war" are as follows:

       

       

                java:global/admshow/JpaUserDao!de.comp.dao.UserDao

                java:app/admshow/JpaUserDao!de.comp.dao.UserDao

                java:module/JpaUserDao!de.comp.dao.UserDao

                java:global/admshow/JpaUserDao

                java:app/admshow/JpaUserDao

                java:module/JpaUserDao

       

       

      17:47:18,029 INFO  [org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor] (MSC service thread 1-9) JNDI bindings for session bean named UserCreate in deployment unit deployment "admshow.war" are as follows:

       

       

                java:global/admshow/UserCreate!de.comp.admin.UserCreate

                java:app/admshow/UserCreate!de.comp.admin.UserCreate

                java:module/UserCreate!de.comp.admin.UserCreate

                java:global/admshow/UserCreate

                java:app/admshow/UserCreate

                java:module/UserCreate

       

       

      17:47:18,049 INFO  [org.jboss.weld.deployer] (MSC service thread 1-11) JBAS016005: Starting Services for CDI deployment: admshow.war

      17:47:18,053 INFO  [org.jboss.as.jpa] (MSC service thread 1-11) JBAS011402: Starting Persistence Unit Service 'admshow.war#jatPU'

      17:47:18,056 INFO  [org.hibernate.ejb.Ejb3Configuration] (MSC service thread 1-11) HHH000204: Processing PersistenceUnitInfo [

                name: jatPU

                ...]

      17:47:18,062 INFO  [org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator] (MSC service thread 1-11) HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider

      17:47:18,066 INFO  [org.hibernate.dialect.Dialect] (MSC service thread 1-11) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect

      17:47:18,067 INFO  [org.hibernate.engine.transaction.internal.TransactionFactoryInitiator] (MSC service thread 1-11) HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory

      17:47:18,068 INFO  [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (MSC service thread 1-11) HHH000397: Using ASTQueryTranslatorFactory

      17:47:18,078 INFO  [org.hibernate.tool.hbm2ddl.SchemaValidator] (MSC service thread 1-11) HHH000229: Running schema validator

      17:47:18,079 INFO  [org.hibernate.tool.hbm2ddl.SchemaValidator] (MSC service thread 1-11) HHH000102: Fetching database metadata

      17:47:18,082 INFO  [org.hibernate.tool.hbm2ddl.TableMetadata] (MSC service thread 1-11) HHH000261: Table found: kds.user

      17:47:18,083 INFO  [org.hibernate.tool.hbm2ddl.TableMetadata] (MSC service thread 1-11) HHH000037: Columns: [loginname, activesince, timelastupdate, lastpasswordchange, userid, lastname, firstname, isbarred, password, lastpasswordchangeby, lastaccess, isadmin]

      17:47:18,085 WARN  [org.hibernate.internal.SessionFactoryImpl] (MSC service thread 1-11) HHH000008: JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession() <== could that be a cause?

      17:47:18,087 INFO  [org.jboss.weld.deployer] (MSC service thread 1-3) JBAS016008: Starting weld service for deployment admshow.war

      17:47:18,136 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (MSC service thread 1-1) Mojarra 2.1.5 (SNAPSHOT 20111202) f?r Kontext '/admshow' wird initialisiert.

      17:47:18,285 INFO  [org.jboss.web] (MSC service thread 1-1) JBAS018210: Registering web context: /admshow

      17:47:18,290 INFO  [org.jboss.as.server] (management-handler-threads - 44) JBAS018562: Redeployed "admshow.war"

      17:47:18,291 INFO  [org.jboss.as.server] (management-handler-threads - 44) JBAS018565: Replaced deployment "admshow.war" with deployment "admshow.war"

        • 1. Re: Transaction demarcation - automatic flush
          Dominik Grupp Newbie

          I increased the log level and found the following (I transferred the kitchensink-quickstart example from JBoss to my own application so it does have as well a Member table in the database). Google shows only Spring-related issues / solutions but I do not use Spring at all. Do I have to? I thought the container is taking care of transaction demarcation. How can I solve that issue?

           

          Any help much appreciated!!!

           

          20:34:20,059 FEIN  [javax.enterprise.resource.webcontainer.jsf.lifecycle] (http--127.0.0.1-8080-2) Entering InvokeApplicationsPhase

          20:34:20,060 FEIN  [javax.enterprise.resource.webcontainer.jsf.application] (http--127.0.0.1-8080-2) processAction(register)

          20:34:20,063 DEBUG [org.jboss.as.ejb3] (http--127.0.0.1-8080-2) Looking for stateful component instance with session id: {[-65, -15, -98, 91, 0, -82, 77, 57, -118, 70, 61, 73, -12, -125, -45, 50]}

          20:34:20,064 INFO  [org.jboss.as.quickstarts.kitchensink.controller.MemberRegistration] (http--127.0.0.1-8080-2) Registering asdfasdfasdf

          20:34:20,066 DEBUG [org.hibernate.internal.SessionImpl] (http--127.0.0.1-8080-2) Opened session at timestamp: 13316672600

          20:34:20,066 DEBUG [org.jboss.as.jpa] (http--127.0.0.1-8080-2) http--127.0.0.1-8080-2:[transaction scoped EntityManager]: created entity manager session TransactionImple < ac, BasicAction: 0:ffffc0a8b216:-37a4a0fb:4f5fa08b:2f status: ActionStatus.RUNNING >

          20:34:20,074 DEBUG [org.hibernate.event.internal.AbstractSaveEventListener] (http--127.0.0.1-8080-2) Delaying identity-insert due to no transaction in progress

          20:34:20,077 INFO  [org.jboss.as.quickstarts.kitchensink.data.MemberListProducer] (http--127.0.0.1-8080-2) triggering now retrieveAllMembersOrderedByName()

          20:34:20,078 INFO  [org.jboss.as.quickstarts.kitchensink.data.MemberListProducer] (http--127.0.0.1-8080-2) executing now retrieveAllMembersOrderedByName()

          20:34:20,079 DEBUG [org.jboss.as.jpa] (http--127.0.0.1-8080-2) http--127.0.0.1-8080-2:[transaction scoped EntityManager]: reuse entity manager session already in tx TransactionImple < ac, BasicAction: 0:ffffc0a8b216:-37a4a0fb:4f5fa08b:2f status: ActionStatus.RUNNING >

          20:34:20,081 DEBUG [org.jboss.as.jpa] (http--127.0.0.1-8080-2) http--127.0.0.1-8080-2:[transaction scoped EntityManager]: reuse entity manager session already in tx TransactionImple < ac, BasicAction: 0:ffffc0a8b216:-37a4a0fb:4f5fa08b:2f status: ActionStatus.RUNNING >

          20:34:20,082 DEBUG [org.hibernate.ejb.criteria.CriteriaQueryCompiler] (http--127.0.0.1-8080-2) Rendered criteria query -> select generatedAlias0 from Member as generatedAlias0 order by generatedAlias0.name asc

          20:34:20,083 DEBUG [org.hibernate.engine.jdbc.internal.LogicalConnectionImpl] (http--127.0.0.1-8080-2) Obtaining JDBC connection

          20:34:20,084 DEBUG [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (http--127.0.0.1-8080-2) MySqlDSjsfadmin: getConnection(null, null) [10/99]

          20:34:20,085 DEBUG [org.hibernate.engine.jdbc.internal.LogicalConnectionImpl] (http--127.0.0.1-8080-2) Obtained JDBC connection

          20:34:20,086 DEBUG [org.hibernate.SQL] (http--127.0.0.1-8080-2)

              /* select

                  generatedAlias0

              from

                  Member as generatedAlias0

              order by

                  generatedAlias0.name asc */ select

                      member0_.id as id1_,

                      member0_.email as email1_,

                      member0_.name as name1_,

                      member0_.phone_number as phone4_1_

                  from

                      Member member0_

                  order by

                      member0_.name asc

          20:34:20,092 DEBUG [org.hibernate.loader.Loader] (http--127.0.0.1-8080-2) Result set row: 0

          20:34:20,092 DEBUG [org.hibernate.loader.Loader] (http--127.0.0.1-8080-2) Result row: EntityKey[de.comp.domain.Member#1]

          20:34:20,093 DEBUG [org.hibernate.engine.internal.TwoPhaseLoad] (http--127.0.0.1-8080-2) Resolving associations for [de.comp.domain.Member#1]

          20:34:20,094 DEBUG [org.hibernate.engine.internal.TwoPhaseLoad] (http--127.0.0.1-8080-2) Done materializing entity [de.comp.domain.Member#1]

          20:34:20,095 DEBUG [org.hibernate.engine.internal.StatefulPersistenceContext] (http--127.0.0.1-8080-2) Initializing non-lazy collections

          20:34:20,096 DEBUG [org.jboss.as.jpa] (http--127.0.0.1-8080-2) http--127.0.0.1-8080-2:[transaction scoped EntityManager]: closing entity managersession

          20:34:20,097 DEBUG [org.hibernate.engine.jdbc.internal.LogicalConnectionImpl] (http--127.0.0.1-8080-2) Releasing JDBC connection

          20:34:20,097 DEBUG [org.jboss.jca.core.connectionmanager.pool.strategy.OnePool] (http--127.0.0.1-8080-2) MySqlDSjsfadmin: returnConnection(1139c27, false) [10/98]

          20:34:20,098 DEBUG [org.hibernate.engine.jdbc.internal.LogicalConnectionImpl] (http--127.0.0.1-8080-2) Released JDBC connection

          20:34:20,099 DEBUG [org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler] (http--127.0.0.1-8080-2) HHH000163: Logical connection releasing its physical connection

          20:34:20,100 FEIN  [javax.enterprise.resource.webcontainer.jsf.lifecycle] (http--127.0.0.1-8080-2) Exiting InvokeApplicationsPhase

          • 2. Re: Transaction demarcation - automatic flush
            Dominik Grupp Newbie

            Solution: never use transaction-type=RESOURCE_LOCAL in a JavaEE environment but only JTA (http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/configuration.html)!