Drools 规则条件 - 检查属性是否为空

Drools rule condition - check if attribute is null

我有一个相当简单的案例,我想在我的规则条件中检查属性是否不为空。

rule "only do action if attribute is not null"
when
    $fact : Fact(attribute!=null, $attribute : attribute)
then
    rulesLogger.debug("Rule fires = " + $attribute);
end

我已经在调试中追踪到这一点。正在插入属性为 null 的事实,但规则仍会触发。控制台输出如下

Rule fires = null

如果我将条件更改为 attribute==null,则规则不会触发。所以它似乎与我期望的完全相反。

我们确实有一个使用函数解决此问题的方法,但它有点难看,我无法弄清楚为什么它首先不起作用。

function Boolean attributeExists(Fact fact)
{
    if(fact.getAttribute() == null)
    {
        return Boolean.FALSE;
    }
    else
    {
        return Boolean.TRUE;
    }
}

rule "only do action if attribute is not null"
when
    $fact : Fact($attribute : attribute)
    Boolean(booleanValue == true) from attributeExists($fact)
then
    rulesLogger.debug("Rule fires = " + $attribute);
end

编辑 1

drools 版本是 5.3.0。

事实是通过使用 from 和服务方法调用的另一条规则加载的。我看不到这个事实是无效的,因为它按我期望的方式打印到控制台,并且使用函数的手动解决方法也按预期工作。好奇怪啊

编辑 2

我找到了更好的解决方法。如果我使用 getter 方法访问该属性,则该规则将按预期运行。这看起来比必须编写一个额外的函数要好得多,但仍然很高兴知道为什么在使用 属性 名称时这不起作用。

rule "only do action if attribute is not null"
when
    $fact : Fact(getAttribute()!=null, $attribute : attribute)
then
    rulesLogger.debug("Rule fires = " + $attribute);
end

事实 class 只是一个无聊的 POJO。除了 Object 之外,它没有 superclass 并且没有实现任何接口。它不是 JPA 实体或任何可能存在代理或延迟加载的实体。

尝试其中的一些。我不确定 5.3 是否可以使用 D。

rule "only do action if attribute is not null"
when
  Fact($att: attribute != null)             /* A */
  Fact($att: attribute, eval($att != null)) /* B */
  Fact($att: attribute, attribute != null)  /* C */
  Fact($att: attribute, $att != null)       /* D */
then
  rulesLogger.debug("Rule fires = " + $attribute);
end

强烈建议升级。5.5.0 可能是一个没有代码中断但可以避免类似故障的选项。