gpt4 book ai didi

spring - 如何在新交易中保存实体?

转载 作者:行者123 更新时间:2023-12-05 06:10:19 25 4
gpt4 key购买 nike

我有一个方法可以调用另一个方法来保存带有新事务的实体对象。

public class FooProcessor {
@Transactional
public Foo process(final String id, final String name, final String description) {
final Foo foo = this.fooCreator.createFoo(id, name, description);
foo.setDescription("Change description");
this.fooDAO.save(foo);
return foo;
}
}

process() 正在调用 FooCreator 类中的 createFoo() 方法以使用 @Transactional(propagation = Propagation.REQUIRES_NEW) 创建 foo 对象。

public class FooCreator {
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Foo createFoo(final String id, final String name, final String description) {
return this.fooDAO.save(new Foo(id, name, description));
}

}

当返回的 foo 对象在 process 方法中被修改时,它保存为一个新对象。如何修改 createFoo() 返回的现有 foo 对象?

如果我尝试 findById,它仍然会抛出异常。

public class FooProcessor {
@Transactional
public Foo process(final String id, final String name, final String description) {
final Foo foo = this.fooCreator.createFoo(id, name, description);
final Foo newFoo = fooDAO.findById(foo.getId())
.orElseThrow(() -> new NotFoundException("Foo not found"));
newFoo.setDescription("Change description");
this.fooDAO.save(newFoo);
return newFoo;
}
}

如何在新事务中保存实体并在调用方方法中使用同一实体?

最佳答案

如果未使用适当的隔离级别,您的方法应该无法读取新事务中的更改。如果您将隔离级别设置为 READ_COMMITED,您的处理方法可以读取您的创建者方法的更改。

@Transaction(isolation = Isolation.READ_COMMITTED)
public Foo process(final String id, final String name, final String description) {
}

如果您有一个更严格的隔离级别,事务可能无法读取在 REQUIRED_NEW 事务的方法中所做的更改。举个例子,如果您设置了更严格的 Isolation.SERIALIZABLE,您的代码将给出一个 NotFoundException,因为在 creator 方法中所做的更改无法在 process 方法的事务中读取。

关于spring - 如何在新交易中保存实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64467412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com