首页 > 解决方案 > Drools:使用 Query 获取无状态会话结果

问题描述

由于它来自官方Drools 文档,因此可以使用Query.

// Set up a list of commands
List cmds = new ArrayList();
cmds.add( CommandFactory.newSetGlobal( "list1", new ArrayList(), true ) );
cmds.add( CommandFactory.newInsert( new Person( "jon", 102 ), "person" ) );
cmds.add( CommandFactory.newQuery( "Get People" "getPeople" );

// Execute the list
ExecutionResults results =
  ksession.execute( CommandFactory.newBatchExecution( cmds ) );

// Retrieve the ArrayList
results.getValue( "list1" );
// Retrieve the inserted Person fact
results.getValue( "person" );
// Retrieve the query as a QueryResults instance.
results.getValue( "Get People" );

在下面的示例中,Get People是一个drools Query,它基本上从无状态(!)会话中返回一个对象或对象列表。

在我的项目中,我需要获取一个在 stateless 中创建的对象Kie session,所以我创建了一个Query

query "getCustomerProfileResponse"
    $result: CustomerProfileResponse()
end

CustomerProfileResponse对象正在构建和创建RHS

insert(customerProfileResponse);

我编写了以下代码以批处理模式执行命令并查询结果CustomerProfileResponse

// Creating a batch list
List<Command<?>> commands = new ArrayList<Command<?>>(10);
commands.add(CommandFactory.newInsert(customerProfile));
commands.add(CommandFactory.newQuery(GET_CUSTOMER_PROFILE_RESPONSE, 
GET_CUSTOMER_PROFILE_RESPONSE));

// GO!
ExecutionResults results = kSession.execute(CommandFactory.newBatchExecution(commands));

FlatQueryResults queryResults = (FlatQueryResults) results.getValue(GET_CUSTOMER_PROFILE_RESPONSE); // size() is 0!

queryResults返回一个空列表。

我在 Stack Overflow 上搜索类似的问题,发现无法使用批处理模式对 Drools 中的无状态会话运行查询,因为会话在execute()调用方法后立即关闭,解决方案是注入一个空CustomerProfileResponse对象以及CustomerProfilein要求。

有人可以阐明这个问题吗?

标签: javadroolsstateless

解决方案


在 newInsert 之后和 NewQuery 之前添加 CommandFactory.newFireAllRules() 应该可以解决问题。请参阅http://drools-moved.46999.n3.nabble.com/rules-users-Query-in-stateless-knowledge-session-returns-no-results-td3210735.html

在执行完所有命令之前,您的规则不会触发。即隐含的 fireAllRules() 是所有命令都已执行后。这意味着将在您的规则触发以插入对象之前调用查询。

相反,您需要在执行查询之前添加 FireAllRules 命令。


推荐阅读