我有一个模型对象帐户
package com.drool.model;
import java.util.Date;
public class Acccount {
private int id;
private int balance;
private Date transDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public Date getTransDate() {
return transDate;
}
public void setTransDate(Date transDate) {
this.transDate = transDate;
}
}
DroolsRule
import com.drool.model.Acccount
rule "accountTransaction"
when
$first : Acccount()
$second : Acccount( this != $first, transDate==$first.transDate )
then
System.out.println("second Accounbt had latest transaction");
end
测试应用程序代码:
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("HelloWorld.drl"), ResourceType.DRL);
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
Acccount account = new Acccount();
account.setBalance(1000000);
account.setId(123);
account.setTransDate(new Date());
Acccount account1 = new Acccount();
account1.setBalance(200);
account1.setId(1234);
account1.setTransDate(new Date());
ksession.insert(account);
ksession.insert(account1);
ksession.fireAllRules();
输出:
second Accounbt had latest transaction
second Accounbt had latest transaction
我是drools的新手,当我运行上面的示例时。结果打印两次,理想情况下只打印一次。如果我的规则是正确的,请告诉我?
答案 0 :(得分:0)
像这样的一对约束:
$first : Acccount()
$second : Acccount( this != $first, transDate==$first.transDate )
如果它完全发射,必然会发射两次。由于同一日期的两个Acccount事实,事实A被绑定到$first
,因此事实B被匹配并绑定到$second
。但是A和B的对称性并没有被约束所打破,因此同样的事情再次发生,A和B交换角色。
要避免这种情况,请使用具有排序关系的唯一属性,大概是id
:
$first : Acccount( $id1: id )
$second : Acccount( id > $id1, transDate==$first.transDate )
答案 1 :(得分:-2)
如果您想使用“帐户(名称=”格式)比较同一班级的两个实例,您会怎么做。