如何从java代码中的guvnor规则获取输出结果

时间:2013-07-31 05:49:15

标签: java drools drools-guvnor

我在guvnor上传了一个患者模型jar,该类有名称和结果字段。

我在guvnor中创建了一个规则,只要名称具有特定值,就将结果作为“pass”插入:规则代码如下:

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

以下是调用此规则的java代码。

        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());

但是当我运行此代码时,我得到相同的名称和结果字符串为null。所以我在这里犯了什么错误。

基本上我只需要一种方法来调用一个简单的规则并使用java显示结果。是否有任何示例证明它。

1 个答案:

答案 0 :(得分:1)

问题是,在您的规则中,您正在创建一个新的Patient实例,而不是修改现有的实例。 您需要做的是绑定匹配的患者并在您的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

希望它有所帮助,