基本规范
基本模式
rule “name”
when 条件部分LHS then RHS结果部分
样例:
rule "rule1"
when
$customer:Customer(age>20,gender==’male’)
Order(customer==$customer,price>1000)
then
<action>…
End
Fact对象
具有若干个属性及其对应的getter setter方法的javabean对象
declare Address
city : String
addressName : String
end
与下面的java代码等价
public class Address {
private String city;
private String addressName;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddressName() {
return addressName;
}
public void setAddressName(String addressName) {
this.addressName = addressName;
}
}
条件部分LHS
约束连接
&&(and) ||(or) ,(and)
注意:
“,”不能 和“&&” “||” 混合使用
比较运算符
>, >= ,< ,<=, ==, !=, contains, not contains, memberof , not memberof ,matches, not matches等
contians
contians样例:
package test
rule "rule1"
when
$order:Order();
$customer:Customer(age >20, orders contains $order);
then
System.out.println($customer.getName());
End
注意事项
contains 只能用于对象的某个Collection/Array 类型的字段与另外一个值进行比较,作为比较的值可以是一个静态的值,也可以是一个变量(绑定变量或者是一个global 对象)。
not contains
与contains作用相反
memberOf/not memverOf
用法与contains 有些类似,但也有不同,memberOf 的语法如下:
Object(fieldName memberOf value[Collection/Array])
可以看到memberOf 中集合类型的数据是作为被比较项的,集合类型的数据对象位于memberOf 操作符后面,同时在用memberOf 比较操作符时被比较项一定要是一个变量
matches/not matches
matches 用于对某个Fact字段的java正则表达式进行想死匹配
Object(fieldName matches “正则表达式”)
样例:
package test
import java.util.List;
rule "rule1"
when
$customer:Customer(name matches "张.*");
then
System.out.println($customer.getName());
end
结果部分RHS
insert():
格式:
insert(new Object());
insertLogical():
将Fact对象插入到当前的WorkingMemory中
update()
retract()
drools()
kcontext()
modify()
因考虑不周调用insert、update 或retract容易发生死循环
package test
import java.util.List;
rule "rule1"
salience 2
when
eval(true);
then
Customer cus=new Customer();
cus.setName("张三");
insert(cus);
end
rule "rule2"
salience 1
when
$customer:Customer(name =="张三");
then
System.out.println("rule2----"+$customer.getName());
end
查询
以query关键字开头,以end关键字结束
query "query name"
conditions
End
有条件查询
query "query name" (Object obj,...)
conditions
end
外部参数传入
query "testQuery"(int $age,String $gender)
customer:Customer(age>$age,gender==$gender)
end
元数据声明
@metadata_key( metadata_value )
在这里metadata_value 属性值是可选的。具体实例如下:
@author(gaojie)
这个元数据属性名为author,值为gaojie。
declare User
@author(gaojie)
@createTime(2009-10-25)
username : String @maxLenth(30)
userid : String @key
birthday : java.util.Date
end
代码是一个元数据在通过declare 关键字声明对象时的具体应用实例,在这个例子当中,一共有四个元数据的声明,首先对于User 对象有两个元数据的声明:author 说明这个对象的创建者是gaojie;createTime 说明创建的时间为2009-10-25 日。接下来是对User
对象的username 属性的描述,说明该属性的maxLenth 的值为30。最后是对userid 属性的描述,注意这个描述只有一个无数据的属性名key,而没有为这个属性key 赋于具体的值。