为什么@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)不提交?

时间:2016-02-12 11:49:09

标签: java jpa java-ee transactions java-ee-7

我有OwnerService类,其中包含以下代码:

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()返回null。我想原因是方法doRegisterOwner没有提交对数据库的更改。我不知道它是特征还是错误,但我仍然想让它发挥作用。

1 个答案:

答案 0 :(得分:3)

这是设计的。只有外部调用(即来自通过容器的代理/拦截系统的其他bean的调用)才会尊重任何属性。

如果您希望在新事务中调用GameObject[] cubeParticules; void OnTriggerEnter() { foreach(GameObject part in cubeParticules) { Instantiate(part, temp1, Quaternion.identity); } } ,请将该代码移动到另一个会话bean。或者只需将注释移至doRegisterOwner中的公开registerOwner方法。