Search code examples
drools

Can I trigger an update of a fact in drools programmatically?


Is there a way to update a fact in drools programmatically? I mean, instead of something like

...
then
    $myFact.setNewValue("newValue");
    update($myFact);

Can I define a function that would take my fact and e.g. the RuleContext (I couldn't find it there) or some other drools specific interface to update a fact?

...
    $myFact.setNewValue("newValue");
    myFunction($myFact, someDroolsInterface);

while the myFunction would then call for an update of the given fact using someDroolsInterface (or is there any other way to do this as part of the consequence but without having it in the drools rule file itself)?

Is this possible?

Thanks for any tips!


Solution

  • After searching and debugging for a while I found that there is

    org.drools.core.spi.KnowledgeHelper
    

    (see e.g. http://javadox.com/org.drools/drools-core/6.2.0.Final/org/drools/core/spi/KnowledgeHelper.html )

    This does allow to do insert() and update() amongst other things.

    I used it e.g. somewhat like this in the rule (pseudo code!) making use of the always exposed "kcontext" RuleContext:

    ...
    then
        myService.doSomeServiceCall(kcontext, $myFact1, $myFact2);
    

    Inside my service call I then had some helper methods like so:

    protected void updateFacts(final KnowledgeHelper helper, final Object... facts)
    {
        for (final Object fact : facts)
        {
            helper.update(fact);
        }
    }
    

    Important for this to work is that the facts correctly implement the equals/hashCode methods in order for this lookup of the fact to work (as I didn't have fact handles available).