Search code examples
drools

Activate Rules on child objects in Drools


I have two Facts named OptionalCover and OptionalPremiumComponent and OptionalCover has a reference of OptionalPremiumComponent in it. So this is what I'm inserting into working memory.

private static OptionalCover getOptionalCover(Double sumAssured, Double premiumRate) {
    OptionalPremiumComponent premiumComponent = new OptionalPremiumComponent();
    premiumComponent.setSumAssured(sumAssured);
    premiumComponent.setPremiumRate(premiumRate);

    OptionalCover optionalCover = new OptionalCover();
    optionalCover.setPremiumComponent(premiumComponent);
    return optionalCover;
}

kieSession.insert(getOptionalCover(1000000.0, 0.02));

I have created the following rule in drools

import java.lang.Number;

rule "OptionalCoverCalculation"
    dialect "java"
    when
        opc : OptionalPremiumComponent( sumAssured > 1I && sumAssured != null && premiumRate != null && premiumRate > 0.0 )
    then
        opc.setPremium( opc.getSumAssured() * 0.001 * opc.getPremiumRate() );
        System.out.println("Here");
end

The problem is, the above rule is not being fired when I insert the parent object. Do I have to do anything else to enable this behaviour? Is it supported?

Thank you.


Solution

  • The Drools engine has no way of telling that your Cover contains a Component. (Well, it has, as it might use reflection - but where should it stop?)

    So, you'll have to insert the OptionalPremiumComponent as well.

    To reduce the amount of clutter in your code you might write a sorts of clever methods so that you can insert Cover and Component with a single call. For instance, if you have many similar "contains" relationships and if you want to reason freely, you might implement s.th. like

    interface FactContainer {
         List<Object> factChildren(); -- return all contained fact objects
         -- OR --
         void insertAll( KieSession ks );
    }
    

    where factChildren would return a List with the premiumComponent or an empty List, or, alternatively, one method insertAll that handles everything internally.