The typical misunderstanding is that a global is a "variable" in the
usual sense of the word. It is not.
When you set a global, you store an object in a map, using the
global's name as a key. Using a global in DRL code perfidiously and
conveniently hides the way the global is made available to the code in
a rule when you use the global's name just like any other variable:
You write the global's name, but you use a local copy.
If you intend to change the global existence of a global you'll have
to use the API that's used to set up a global in the first place: get
the session object, call setGlobal...
Cheers
Wolfgang
On 03/02/2014, milen igrachev <igrachev(a)abv.bg> wrote:
Hello, for the first time I have the need to define a global
variables in a
DRL file, and from what it seems from the documentation it shall be a
variable visible to all my rules in the
DRL file. However I don't see what I do wrong, but the modifications made by
one rule are not visible to the others. Here is illustration of what I
have:
[Fact model code]
public class TestPOJO { private int fieldOne; private String
fieldTwo; public int getFieldOne() {...} public void
setFieldOne(int fieldOne) {...} public String getFieldTwo() {...}
public void setFieldTwo(String fieldTwo) {...} }
[DRL rule code]
global java.lang.Double myGlobal; rule "Your First Rule" salience 2
when
TestPOJO(fieldOne > 10)
then
System.out.println("This is rule #1");
System.out.println(myGlobal);
myGlobal = 0.03; end rule "Your Second Rule" salience 1
when
TestPOJO(fieldTwo == "true")
then
System.out.println("This is rule #2");
System.out.println(myGlobal); end
[Call to Drools]
TestPOJO myTestFact = new TestPOJO(); myTestFact.setFieldOne(15);
myTestFact.setFieldTwo("true");
KieServices ks = KieServices.Factory.get(); KieContainer kContainer =
ks.getKieClasspathContainer(); KieSession kSession =
kContainer.newKieSession("ksession-rules");
kSession.insert(myTestFact); kSession.fireAllRules();
kSession.dispose();
[Output]
This is rule #1 null This is rule #2 null
[What I expect to have as output] This is rule #1 null This is rule #2
0.03
I used the salience to set rule order to be sure that rule one is executed
before rule two, but my global value is never updated.
Can you please tell me where I do wrong? Can my expectations be met somehow,
I need such type of internal rule variables to calculate temporary
values and pass them between rules?
Thank you!!!
Best Regards, Milen