Drools最基本最常用的有以下四种
布尔运算与数值运算规则
rule "Add 5% discount for minors or seniors"
when $o: Order(customer.age < 18 || customer.age > 60)
then $o.increaseDiscount(0.05);
end
基于集合的规则
(contains and memberOf) 他们主要用来检测集合是否包含不包含某元素
rule "print orders with pencils in them"
when
$i: Item(name == "pencil")
$ol: OrderLine(item == $i)
$o: Order($ol memberOf orderLines,
orderLines contains $ol)
then
System.out.println("order with pencils: " + $o);
end
from: 找到集合里面对应条件的数据
rule "match all famale by from"
when
Company($persons: persons)
$p:Person(gender == Person.GENDER_FEMALE) from $persons
then
System.out.println("girl'name is " + $p.getName());
end
Person p = new Person();
p.setName("Wang");
p.setGender(Person.GENDER_FEMALE);
Person p2 = new Person();
p2.setName("Depu");
p2.setGender(Person.GENDER_MALE);
List<Person> persons = new ArrayList<>();
persons.add(p);
persons.add(p2);
Company c = new Company();
c.setPersons(persons);
ks.insert(c);
collect(以下的代码的意思是把是Person对象的都集中起来放在一个List里面)
rule "match all famale by collect"
when
$grils:List(size>0) from collect(Person(name=="Depu"))
then
System.out.println("gril's size " + $grils.size());
end
@Test
public void testCollect() {
Person p = new Person();
p.setName("Wang");
p.setGender(Person.GENDER_FEMALE);
Person p2 = new Person();
p.setName("Depu");
p.setGender(Person.GENDER_MALE);
ks.insert(p);
ks.insert(p2);
int count = ks.fireAllRules();
System.out.println("total run " +count+ " rules");
}
正则匹配规则
rule "validate customer emails"
when
$c: Customer(email not matches "[A-Za-z0-9-.]+@[A-Za-z0-9-.]+$")
then
$c.setEmail(null); //invalidate email
end
Accumulate 关键字 这是一个很强大的功能,它提供了强大的过滤功能,比如用户A有一批订单,用户实体类里面有一个集合是存储的订单,通过这个关键字可以根据订单的字段过滤出符合条件的订单
以下的代码表达的意思是,对Account类的balance求平均值,将最终的计算结果放在$averageBalancez中
query averageBalanceQuery
Number( $averageBalance : doubleValue ) from accumulate(
$account : Account($balance : balance), average($balance))
end
@Test
@Parameters("17.00,50.0,22.0,5.0")
public void testAverage(double val1, double val2, double val3, double val4){
ks.fireAllRules();
System.out.println(getAverageBalance());// 0.0
ks.insert(new Account(val1));
ks.insert(new Account(val2));
ks.insert(new Account(val3));
ks.insert(new Account(val4));
System.out.println(getAverageBalance());// 23.5
}
BigDecimal getAverageBalance() {
QueryResults queryResults = ks.getQueryResults("averageBalanceQuery");
return BigDecimal.valueOf((Double) queryResults
.iterator().next().get("$averageBalance"));
}