How to break the loops in Drools, Mvel dialect?

890 Views Asked by At

In the below rule the logic in then-part is getting executed for all Child-objects which pass the given condition, I want to break the loop after the logic in then-part is executed only once, how to do this

rule "test"
            when
                Parent( $childList : childList != null, childList.empty == false)
                Child('testing'.equalsIgnoreCase(attribute)) from $childList
            then
                // testLogic
end
2

There are 2 best solutions below

1
Esteban Aliverti On

If you don't need a reference to the Child object (or any of its attributes) in the RHS, then you can use an exists operator:

rule "test"
when
 Parent( $childList : childList != null, childList.empty == false)
 exists Child('testing'.equalsIgnoreCase(attribute)) from $childList
then
 // testLogic
end

If for some reason you do need the Child object or any of its attributes you can do something like this (although is not very nice):

rule "test"
when
 Parent( $childList : childList != null, childList.empty == false)
 $c: Child('testing'.equalsIgnoreCase(attribute)) from $childList.get(0)
then
 // testLogic
end

Hope it helps,

1
kavita On

Reason for infinite loop should be known by identifying whether it is self-loop or complex-loop.

  • Fact modification within the rule activates the same rule (Self)
  • Fact modification within the rule activates the different rule (complex) and it activates the original rule.

You can use 'no-loop', next to rule name as no-loop true

You can also restrict by using agenda-group, by checking conditions or like a flag. It depends upon your complexity.