为什么 @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) 不提交?
Why @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) does not commit?
我有 OwnerService
class 其中包含此代码:
public RegisterOwnerResult registerOwner(RegisterOwnerRequest request) {
try {
Owner owner = doRegisterOwner(request);
return RegisterOwnerResult.createSuccessful(owner.getId());
} catch (Exception ex) {
return RegisterOwnerResult.createUnsuccessful();
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private Owner doRegisterOwner(RegisterOwnerRequest request) {
Account account = new Account(request.getEmail(), request.getPassword());
Owner owner = new Owner(account, request.getFirstName(), request.getLastName());
ownerFacade.create(owner);
return owner;
}
和启动数据库的 Startup Singleton bean:
@PostConstruct
public void initiate() {
RegisterOwnerRequest registerOwnerRequest = new RegisterOwnerRequest(
"john.barton@example.com",
"pass123",
"John",
"Barton"
);
RegisterOwnerResult registerOwnerResult = ownerService.registerOwner(registerOwnerRequest);
if (registerOwnerResult.wasSuccessful()) {
System.out.println("Owner ID: " + registerOwnerResult.getOwnerId());
}
}
但不幸的是 registerOwnerResult.getOwnerId() returns 无效。我想原因是方法 doRegisterOwner
没有提交对数据库的更改。我不知道它是功能还是错误,但我还是想让它工作。
这是设计使然。只有外部调用(即来自通过容器的 proxy/interception 系统的其他 bean 的调用)尊重任何属性。
如果您希望在新事务中调用 doRegisterOwner
,请将该代码移至另一个会话 bean。或者干脆把注解移到OwnerService
.
中的publicregisterOwner
方法
我有 OwnerService
class 其中包含此代码:
public RegisterOwnerResult registerOwner(RegisterOwnerRequest request) {
try {
Owner owner = doRegisterOwner(request);
return RegisterOwnerResult.createSuccessful(owner.getId());
} catch (Exception ex) {
return RegisterOwnerResult.createUnsuccessful();
}
}
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
private Owner doRegisterOwner(RegisterOwnerRequest request) {
Account account = new Account(request.getEmail(), request.getPassword());
Owner owner = new Owner(account, request.getFirstName(), request.getLastName());
ownerFacade.create(owner);
return owner;
}
和启动数据库的 Startup Singleton bean:
@PostConstruct
public void initiate() {
RegisterOwnerRequest registerOwnerRequest = new RegisterOwnerRequest(
"john.barton@example.com",
"pass123",
"John",
"Barton"
);
RegisterOwnerResult registerOwnerResult = ownerService.registerOwner(registerOwnerRequest);
if (registerOwnerResult.wasSuccessful()) {
System.out.println("Owner ID: " + registerOwnerResult.getOwnerId());
}
}
但不幸的是 registerOwnerResult.getOwnerId() returns 无效。我想原因是方法 doRegisterOwner
没有提交对数据库的更改。我不知道它是功能还是错误,但我还是想让它工作。
这是设计使然。只有外部调用(即来自通过容器的 proxy/interception 系统的其他 bean 的调用)尊重任何属性。
如果您希望在新事务中调用 doRegisterOwner
,请将该代码移至另一个会话 bean。或者干脆把注解移到OwnerService
.
registerOwner
方法