There are a lot of Drools Flow users that ask us about how to use Drools Flow persistence without JTA transactions, so in order to give those users a proper answer we developed a solution based on the Spring integration. We added support to configure a JpaSessionServiceFactory to the Drools’ configuration namespace. Let’s see how to use it on a real example (you can donwload it from: http://www.plugtree.com/downloads/DroolsFlowSpring.tgz).
Firstly, you need to configure EntityManageFactory and SpringTransactionManager as follows:
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="ds" /> <property name="persistenceUnitName" value="org.drools.persistence.jpa.local" /> </bean> <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="myEmf" /> </bean>
I’m not showing the datasource configuration because it heavily depends on your deployment but you can grab it from the example
.
Secondly, you have to define a kbase that then would be used by the JpaSessionService:
<drools:kbase id="kbase1"> <drools:resource type="DRF" source="classpath:VariablePersistenceStrategyProcess.rf" /> </drools:kbase>
And finally, you need to define the JpaSessionService:
<drools:jpaSessionServiceFactory id="jpaSingleSessionCommandService" kbase="kbase1" entityManagerFactory="myEmf" transactionManager="txManager"> <drools:variablePersisters> <drools:persister forClass="javax.persistence.Entity" implementation="org.drools.persistence.processinstance.persisters.JPAVariablePersister"/> <drools:persister forClass="java.lang.String" implementation="org.plugtree.labs.variablepersistence.StringVariablePersister"/> <drools:persister forClass="java.io.Serializable" implementation="org.drools.persistence.processinstance.persisters.SerializableVariablePersister"/> </drools:variablePersisters> </drools:jpaSessionServiceFactory>
Bear in mind if that you don’t need to define customs variable persisters the configuration it’s only one line!.
Then you can inject it to your own beans or create a Spring Context manually, as shown in the this snippet:
ctx = new ClassPathXmlApplicationContext("beans.xml");
JPASingleSessionCommandService jpaService = (JPASingleSessionCommandService) ctx
.getBean("jpaSingleSessionCommandService");
SingleSessionCommandService service = jpaService.newStatefulKnowledgeSession();
int sessionId = service.getSessionId();
....
//do something
service.dispose();
Then in a future time retrieve the session:
SingleSessionCommandService service = jpaService.loadStatefulKnowledgeSession(sessionId);
//do something
....
service.dispose();
Warning note: when you use the flow persistence with JTA, it automatically reloads the state out the session after a rollback. We couldn’t do that behavior here since simple database connections doesn’t provide a listener mechanism as JTA transactions does.
Tags: PlugTree Drools Flow