前奏
群组(QQ:593177274)交流中有朋友提出一个问题,怎么实现两个相同对象的插入和比较?相信很多朋友也遇到类似的问题,于是抽时间为大家写一段实例代码,后续代码会同步到GitHub中。下面简单介绍一下实现实例:
场景
向session中insert两个相同的对象,但对象的参数值有不同的地方,同时要求对两个FACT对象的属性进行判断,当同时满足(&&)时,通过规则校验,进行后续业务处理。下面,通过两种方式来实现此功能。
代码实现
方式一
规则文件内容:
package com.rules import com.secbro.drools.model.Customer; rule "two same objects" agenda-group "two same objects" when $firstCustomer:Customer(age == 59); $secondCustomer:Customer(this != $firstCustomer,age == 61); then System.out.println("firstCustomer age :" + $firstCustomer.getAge()); System.out.println("secondCustomer age :" + $secondCustomer.getAge()); end
测试端调用部分代码:
@Test public void testSameObjects() { KieSession kieSession = getKieSession("two same objects"); Customer customer = new Customer(); customer.setAge(61); kieSession.insert(customer); Customer customer1 = new Customer(); customer1.setAge(59); kieSession.insert(customer1); int count = kieSession.fireAllRules(); kieSession.dispose(); System.out.println("Fire " + count + " rules!"); }
如此,则实现了上面场景的内容。值得注意的是规则文件中this != $firstCustomer的写法,此处可以排除两个对象属性相同导致的问题。
方法二
此方式采用List来传递两个相同的参数,规则文件内容如下:
package com.rules import com.secbro.drools.model.Customer; import java.util.List; rule "two same objects in list" agenda-group "two same objects in list" when $list : List(); $firstCustomer:Customer(age == 59) from $list; $secondCustomer:Customer(this != $firstCustomer,age == 61) from $list; then System.out.println("two same objects in list:firstCustomer age :" + $firstCustomer.getAge()); System.out.println("two same objects in list:secondCustomer age :" + $secondCustomer.getAge()); end
测试类部分代码:
@Test public void testSameObjectsInList() { KieSession kieSession = getKieSession("two same objects in list"); List<Customer> list = new ArrayList<>(); Customer customer = new Customer(); customer.setAge(61); list.add(customer); Customer customer1 = new Customer(); customer1.setAge(59); list.add(customer1); kieSession.insert(list); int count = kieSession.fireAllRules(); kieSession.dispose(); System.out.println("Fire " + count + " rules!"); }