query 作用和语法
Drools 因其他灵活的 LHS 语法, 能实现非常强大的模式匹配功能, 这是 drools 规则的核心. Drools 通过提供 query
这种方式, 使得我们的java程序也可直接利用其强大的模式匹配功能.
query 定义很简单, 只要写 LHS 部分即可, 语法为:
query "queryName"
LHS
end
示例
drools 文件, 定义了一个无参query和一个带参query:
package com.sample.rules
import com.sample.Order;
query "amount > 10"
$order:Order(amount>10)
end
query "any amount"(int $amount)
$order:Order(amount>$amount)
end
java 端, 调用query的示例
package com.sample;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;
/**
* This is a sample class to launch a rule.
*/
public class DroolsTest {
public static final void main(String[] args) {
try {
// load up the knowledge base
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rules");
Order order = null;
order = new Order();
order.setAmount(2);
kSession.insert(order);
order = new Order();
order.setAmount(20);
kSession.insert(order);
order = new Order();
order.setAmount(3);
kSession.insert(order);
// kSession.fireAllRules(); //call query 不需要fire rule
// 查询无参query
QueryResults queryResults1 = kSession.getQueryResults("amount > 10"); //第一个参数指定query名
for (QueryResultsRow row : queryResults1) {
Order order2 = (Order) row.get("$order");// get row item by bind variable
System.out.println(order2);
}
System.out.println("===========");
// 查询带参query
QueryResults queryResults2 = kSession.getQueryResults("any amount", 10); //第一个参数指定query名, 后面参数作为query的查询参数
for (QueryResultsRow row : queryResults2) {
Order order2 = (Order) row.get("$order");// get row item by bind variable
System.out.println(order2);
}
kSession.dispose();
// System.out.println(order.getRealPrice());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
标签:drools,05,kSession,order,amount,query,Order,row
From: https://www.cnblogs.com/harrychinese/p/drools_05_query.html