Search code examples
javadroolsmvel

In Drools, can a selection clause (using keyword `from`) be written over an Iterable or Iterator?


Given a Java interface like this:

class Hobby {
    public String getName() {...}
}

class Person {
    public Iterable<Hobby> getHobbies() {...}
}

How can I, in a LHS expression, select Hobby objects with a specific name. For example, something like this:

when
    $person: Person()
    $hobby: Hobby(name == "Knitting") from $person.hobbies

Is this supposed to work? It doesn't produce any results when we tried it.

Is there an alternative, given the Java code that returns an Iterable, rather than a Collection?


Solution

  • After fixing the mismatch person/$person, the rule compiles and fires if there is a person with "Knitting" in the hobbies collection. (Version 5.5, but I have no doubt that other versions work just as well.)

    rule "who knits"
    when
      $person: Person( $name: name )
      Hobby(name == "Knitting") from $person.hobbies
    then
      System.out.println( "Knitting: " + $name );
    end
    
    public class Person {
      private String name;
      private List<Hobby> hobbies = new ArrayList<Hobby>();
      public String getName(){
        return name;
      }  
      public Iterable<Hobby> getHobbies(){
         return hobbies;
      }
    }
    

    Also, I don't see any Java interfaces in the snippets you've posted, just two classes.

    If you have a problem, make sure to provide full code to reproduce the example.