为什么Hybris modelService.save()在ifPresent()方法里面不起作用?

问题描述 投票:0回答:1
    private void doSomething(someProcessModel process){
        CustomerModel customer = process.getCustomerModel();

        customer.getFoos().stream()
                .filter(foo -> foo.getCountryCode().equals(process.getCountryCode()))
                .findFirst()
                .ifPresent(foo -> {
                    if(foo.getSomeNumber() == null){
                        foo.setSomeNumber("1234567");
                        modelService.save(foo);
                    }
                });
    }

从上面的代码片段中可以看出,我有一个'CustomerModel',它有一个属性'Foos'。这是一个一对多的关系。如你所见,我做了一些过滤,最后,我想更新'Foo'的'someNumber'属性的值,如果它是空的。我已经确认一切正常,因为 "someNumber "属性的值在调试过程中被更新了。我在HMC中做了检查,根本就没有保存。我也验证了拦截器没有任何条件会抛出一个错误。日志中也没有显示任何内容。

我想知道在'ifPresent()'方法里面做 "modelService.save() "是否合法?这里可能有什么问题?

java-stream optional hybris
1个回答
0
投票

你必须谨慎对待模型中的列表,因为它们是不可改变的,你必须设置整个新的列表。而且你只在一个特定的模型上调用了保存,这改变了它的Jalo引用,这就是为什么你的列表没有更新。突变流和收集它在最后将创建新的列表,这就是为什么你可以直接从模型流过列表。

private void doSomething(someProcessModel process){
    CustomerModel customer = process.getCustomerModel();
    ArrayList<FooModel> foos = doSomethingOnFoos(customer.getFoos());
    customer.setFoos(foos);
    modelService.saveAll(foos, customer);
}

//compare the value you know exists with something that might be NULL as equals can handle that, but not the other way around
private ArrayList<FooModel> doSomethingOnFoos(ArrayList<FooModel> fooList) {
     return fooList.stream()
                .filter(Objects::nonNull)
                .filter(foo -> process.getCountryCode().equals(foo.getCountryCode()))
                .filter(foo -> Objects.isNull(foo.getSomeNumber()))
                .map(foo -> foo.setSomeNumber(1234))
                .collect(toList());
}
© www.soinside.com 2019 - 2024. All rights reserved.