tdudzik
tdudzik

Reputation: 391

Why @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) does not commit?

I have OwnerService class which contain this code:

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;
}

and Startup Singleton bean which should initiate the database:

@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());
    }
}

but unfortunately registerOwnerResult.getOwnerId() returns null. I suppose that the reason is that method doRegisterOwner doesn't commit changes to database. I don't know if it is feature or a bug but nonetheless I'd like to make it work.

Upvotes: 2

Views: 1839

Answers (1)

Alexander Langer
Alexander Langer

Reputation: 2893

This is by design. Only external calls (i.e., calls from other beans that go through the container's proxy/interception system) respect any of the attributes.

If you want calls to doRegisterOwner be in a new transaction, move that code to another session bean. Or simply move the annotation to the public registerOwner method in OwnerService.

Upvotes: 4

Related Questions