KieBase kbase = ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).getKieBase();
UserTransaction ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
KieSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession( kbase, null, env );
ut.commit();
List<?> list = new ArrayList<Object>();
// insert and commit
ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
ksession.setGlobal( "list",
list );
ksession.insert( 1 );
ksession.insert( 2 );
ksession.fireAllRules();
ut.commit();
// insert and rollback
ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
ksession.insert( 3 );
ut.rollback();
// check we rolled back the state changes from the 3rd insert
ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
ksession.fireAllRules();
ut.commit();
assertEquals( 2,
list.size() );
// insert and commit
ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
ksession.insert( 3 );
ksession.insert( 4 );
ut.commit();
// rollback again, this is testing that we can do consecutive rollbacks and commits without issue
ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
ksession.insert( 5 );
ksession.insert( 6 );
ut.rollback();
ksession.fireAllRules();
assertEquals( 4,
list.size() );
// now load the ksession
ksession = JPAKnowledgeService.loadStatefulKnowledgeSession( ksession.getId(), kbase, null, env );
ut = (UserTransaction) new InitialContext().lookup( "java:comp/UserTransaction" );
ut.begin();
ksession.insert( 7 );
ksession.insert( 8 );
ut.commit();
ksession.fireAllRules();
assertEquals( 6,
list.size() );
}