Question

I uploaded a patient model jar on guvnor, the class has name and result field.

I created a rule in guvnor to insert result as "pass" whenever the name has particular value: The code of rule is as below:

rule "IsJohn"
dialect "mvel"
when
    Patient( name == "John")
then
    Patient fact0 = new Patient();
    fact0.setResultString( "Pass" );
    fact0.setName( "Patient: John" );
    insert( fact0 );
end

Below is the java code to call this rule.

        KnowledgeBase knowledgeBase = readKnowledgeBase();
        StatefulKnowledgeSession session = knowledgeBase.newStatefulKnowledgeSession();

        Patient patient = new Patient();

        patient.setName("John");

        System.out.println("patient.name "+patient.getName());
        session.insert(patient);
        session.fireAllRules();

        System.out.println("************patient.name "+patient.getName());
        System.out.println("patient result string is "+patient.getResultString());

But when I run this code I get same name and result string as null. So what mistake am I doing here.

Basically I just need a way through which I can call a simple rule and display back the result using java. Is there any example demonstrating it.

Was it helpful?

Solution

The problem is that, in your rule, you are creating a new instance of Patient instead of modifying the existing one. What you need to do is to bind the matching Patient and use it in your RHS:

rule "IsJohn"
dialect "mvel"
when
    fact0: Patient( name == "John")
then        
    fact0.setResultString( "Pass" );
    fact0.setName( "Patient: John" );
    update( fact0 );   
    // Only do the 'update' if you want other rules to be aware of this change. 
    // Even better, if you want other rules to notice these changes use 'modify' 
    // construct insted of 'update'. From the java perspective, you don't need 
    // to do this step: you are already invoking setResultString() and setName()
    // on the real java object.
end

Hope it helps,

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top