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

Ben*_*ley 5 java drools

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

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

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

Rule fires = null
Run Code Online (Sandbox Code Playgroud)

如果我将条件更改为,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
Run Code Online (Sandbox Code Playgroud)

编辑1

流口水版本是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
Run Code Online (Sandbox Code Playgroud)

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

lau*_*une 2

尝试其中一些。我不确定 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
Run Code Online (Sandbox Code Playgroud)

强烈建议升级。5.5.0 可能是一种不会出现代码中断但可以避免像这样的故障的选项。