13.2. Defining transactions

To define a transaction, do the following:
  1. Register the transaction manager in your environment.

    Example 13.1. Code with transaction manager registration

    // create the entity manager factory
    EntityManagerFactory emf = EntityManagerFactoryManager.get().getOrCreate("org.jbpm.persistence.jpa");
    TransactionManager tm = TransactionManagerServices.getTransactionManager();
    Environment env = EnvironmentFactory.newEnvironment();
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(EnvironmentName.TRANSACTION_MANAGER, tm);
    	
    // setup the runtime environment
    RuntimeEnvironment environment = RuntimeEnvironmentBuilder.Factory.get()
    .newDefaultBuilder()
    .addAsset(ResourceFactory.newClassPathResource("MyProcessDefinition.bpmn2"), ResourceType.BPMN2)
        .addEnvironmentEntry(EnvironmentName.TRANSACTION_MANAGER, tm)
        .addEnvironmentEntry(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, new JpaProcessPersistenceContextManager(env))
        .addEnvironmentEntry(EnvironmentName.TASK_PERSISTENCE_CONTEXT_MANAGER, new JPATaskPersistenceContextManager(env))
        .get();
    
  2. Initialize the KieSession:
    // get the KieSession
    RuntimeManager manager = RuntimeManagerFactory.Factory.get().newPerProcessInstanceRuntimeManager(environment);
    RuntimeEngine runtime = manager.getRuntimeEngine(ProcessInstanceIdContext.get());
    KieSession ksession = runtime.getKieSession();
  3. Define the transaction manager in jndi.properties.

    Example 13.2. Definition of Bitronix transaction manager in jndi.properties

    java.naming.factory.initial=bitronix.tm.jndi.BitronixInitialContextFactory

    Note

    To use a different JTA transaction manager, edit the hibernate.transaction.manager_lookup_class, the transaction manager property, in the persistence.xml file to load your transaction manager.

    Example 13.3. JBoss Transaction Manager set as transaction manager

    <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>
  4. Define the start and the end of the transaction.
     // start the transaction
    UserTransaction ut = InitialContext.doLookup("java:comp/UserTransaction");
    ut.begin();
    
    // perform multiple commands inside one transaction
    ksession.insert( new Person( "John Doe" ) );
    ksession.startProcess("MyProcess");
    
    // commit the transaction
    ut.commit();