简体   繁体   中英

how to compare values of nested object inside a drool rule in java

I have a pojo like below:

class A{
 private List<B> b;
//getters and setters
}

class B{
private String group;
private String status;
//getters and setters
}

I have defined the Drool rule as:

import A;
rule "rule 1"
    ruleflow-group "status"
        when
         
            a : A(b.( group == "ABC", status == "Approved"))
          
        then
            System.out.println("------------Executing rule 1");
           
        end;

rule "rule 2"
    ruleflow-group "status"
    when
       
        a :  A(b.( group == "XYZ", status == "Approved"))
      
    then
        System.out.println("-----------Executing rule 2");
        
    end;

Considering all configurations are in place,when executing the rule, getting below error:

Caused by: org.mvel2.PropertyAccessException: [Error: unable to resolve method: java.util.ArrayList.group() [arglength=0]]

Can someone please help with the modification which I need to do in my rule file so that the nested values are compared.

You've not really described what your use case is, but given your attempt, this is what I interpret you want to do:

  1. Rule 1 should trigger if A contains at least 1 B which has group "ABC" and status "approved".
  2. Rule 2 should trigger if A contains at least 1 B which has group "XYZ" and status "approved".

I further presume the following:

  • Since you don't attempt to extract values or B instances, you don't actually care about the B beyond the fact that it exists.

Your rules would, therefore, look like this:

rule "Rule 1"
when
  A( $bList: b != null )
  exists( B( group == "ABC", status == "approved" ) from $bList )
then
  //...
end

rule "Rule 2"
when
  A( $bList: b != null )
  exists( B( group == "XYZ", status == "approved") from $bList )
then
  // ...
end

In both rules, the first thing we do is extract the sub-list of B's if it is not null. Then we check that there exists at least one B instance which meets your criteria. Since you don't actually do anything with this B instance, we can use the exists operation to simply check for its presence.

If you actually do need to do something with the B instance, you'd assign it to a variable rather than using exists :

rule "Rule 1 with captured B"
when
  A( $bList: b != null )
  $b: B(group == "ABC", status == "approved") from $bList
then
  // can reference $b here
end

Note that this version may trigger multiple times if there are multiple B present which meet your criteria.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM