2 Replies Latest reply on Dec 9, 2009 7:58 AM by Denis Kostousov

    Transaction and EJB3 Singleton

    Denis Kostousov Newbie

      I have a ejb3 project with managed singleton:

      @Service (name = ProfileStateMachine.NAME, objectName = "vis:service=StateMachine")
      @Management (IMainStateMachine.class)
      @Remote (ProfileStateMachine.class)
      public class MainStateMachine implements IMainStateMachine, ProfileStateMachine {
       @PersistenceContext (unitName = "vis")
       private EntityManager entityManager;
      
       void start(){
       SomeEntity entity1=entityManager.find(SomeEntity.class,2);
      
       SomeEntity entity2=new SomeEntity();
       entity2.setFieldOne("one");
       entity2.setFiledTwo("two");
       entityManager.persist(entity2);
       }
      
       void stop(){
       }
      }
      

      interface IMainStateMachine
      public interface IMainStateMachine {
       void start();
      
       void stop();
      
      }


      I receive a exception during project deployment
      Caused by: javax.persistence.TransactionRequiredException: EntityManager must be access within a transaction
       at org.jboss.jpa.deployment.ManagedEntityManagerFactory.verifyInTx(ManagedEntityManagerFactory.java:155)
       at org.jboss.jpa.tx.TransactionScopedEntityManager.persist(TransactionScopedEntityManager.java:186)
      

      The exception is thrown at the persist command
      entityManager.persist(entity2);
      


      I think the start() method is executed before the project was deployed. Same operation ("entityManager.persist()") works well if it is executed after deploy.

      My project has a three stage: starting, working, stopping. I need to use EntityManager during all stages. What I should do to solve the problem?