Search code examples
jpaentitydroolsobject-graph

Drools JPA entity object graph updating


When defining Drools rules, what is the best way to accommodate object graphs?

Say I have the following Entity object graph with a many-to-many relationship:

User <- Group -> Value

and I have the following contrived rule:

rule "hasPurpleValue"
    $u : User()
    $g : Group() from $u.groups
    $v : Value(color == 'Purple') from $g.values
then
    //...
end

I can insert a user into the ksession as follows:

//build user...
User user = new User();
Group group = new Group();
Value value = new Value("Purple");
group.setValue(value);
user.addGroup(group);

ksession.insert(user);

then update them:

ksession.update(ksession.getFactHandle(user), user);

But what if I change the Value object directly to "Orange", the Value does not have a FactHandle as it was inserted with the user as the root. Is there a better way to define the rules and insert the entities such that I can independently alter the Entities and Drools will evaluate the outcome?


Solution

  • You have to make your own choice. As you mentioned in your post, you can't update something that is not a Fact. Every object you insert() is a Fact, but that is not true for nested objects. One way to deal with nested objects is to do what you just did: use the from pattern. The problem of this pattern, as you have described, is that you always have to update() the Fact object related to the real object you are modifying. If you can live with that, then go for it. Another way to deal with this is to insert each object as a Fact: User, Group and Value. This could make your insertion code dirtier, but you will gain in flexibility, readability and, in a way, performance in your rules. So, there is no magic recipe here. You must use what is more convenient for your scenario.

    Hope it helps,