starkk92
starkk92

Reputation: 5924

insert multiple java Objects of same class into drools in java

I am experimenting with drools.

I have come across this situation where I want to insert 2 different java objects of same class into Drools and work with both the objects in each rule.

For Ex:

Lets say I have two java Objects of same class with almost same variables.

class looks something like this.

public class Sample{
   Map<String,String> map;
   sample(Map<String,String>map){
      this.map = map;
   }
}

Objects:

Map<String,String>map1 = new Map<>();
map1.put("name","james");

Map<String,String>map2 = new Map<>();
map2.put("name","james");
map2.put("id","123k");

Sample obj1 = new Sample(map1);
Sample obj2 = new Sample(map2);

The 2 objects obj1,obj2 differ only in the number of keys in the map.

If I insert both these objects into knowledgeSession before running the rules, How can I use both the objects in the same rule?How can I differentiate the objects in the same rule so that I get a chance to work with both the objects in the when clause of the rule.

insertion into session looks something like this:

private static StatefulSession sessionObject;
sessionObject.insert(obj1);
sessionObject.insert(obj2);
sessionObject.fireAllRules(1);

How can I differentiate the objects in the rule so that $obj1 receives object1 and $obj2 receives object2 from the below sample code.

import com.sample.client.Sample;

rule "1"
    when
        $obj1 : Sample()
        $Obj2 : Sample()
        ........
    then
        ........
        ........
end

It is easy to deal with basic datatypes.But How to handle the above case where it is crucial to extract the information of map in the java Object to differentiate the objects?

Upvotes: 2

Views: 2585

Answers (1)

Esteban Aliverti
Esteban Aliverti

Reputation: 6322

If you don't care which object gets bound to which variable, then you can do this:

rule "1"
when
    $obj1 : Sample()
    $obj2 : Sample(this != $obj1)
then

end

If you do need that $obj1 be assigned to obj1 and $obj2 to obj2, then you need something to uniquely identifies your objects. Maybe adding an id attribute to your Sample class or using a specific key in the maps to specify an id. For example:

rule "1"
when
    $obj1 : Sample(map["id"] == "123k")
    $obj2 : Sample(map["id"] == "456k")
then

end

EDIT:

It is important to note that the first rule will still match multiple times even for 2 Sample facts.

Hope it helps,

Upvotes: 3

Related Questions